Python计算dict值中的项目是一个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16864941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python count items in dict value that is a list
提问by RolfBly
Python 3.3, a dictionary with key-value pairs in this form.
Python 3.3,具有这种形式的键值对的字典。
d = {'T1': ['eggs', 'bacon', 'sausage']}
The values are lists of variable length, and I need to iterate over the list items. This works:
这些值是可变长度的列表,我需要遍历列表项。这有效:
count = 0
for l in d.values():
for i in l: count += 1
But it's ugly. There must be a more Pythonic way, but I can't seem to find it.
但它很丑。一定有更Pythonic的方式,但我似乎找不到。
len(d.values())
produces 1. It's 1 list (DUH). Attempts with Counter from heregive 'unhashable type' errors.
产生 1. 它是 1 个列表 (DUH)。从这里尝试使用 Counter会出现“不可哈希类型”错误。
采纳答案by Martijn Pieters
Use sum()and the lengths of each of the dictionary values:
使用sum()和每个字典值的长度:
count = sum(len(v) for v in d.itervalues())
If you are using Python 3, then just use d.values().
如果您使用的是 Python 3,那么只需使用d.values().
Quick demo with your input sample and one of mine:
使用您的输入示例和我的示例之一进行快速演示:
>>> d = {'T1': ['eggs', 'bacon', 'sausage']}
>>> sum(len(v) for v in d.itervalues())
3
>>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
>>> sum(len(v) for v in d.itervalues())
7
A Counterwon't help you much here, you are not creating a count per entry, you are calculating the total length of all your values.
ACounter在这里对您没有多大帮助,您不是在为每个条目创建计数,而是在计算所有值的总长度。
回答by John La Rooy
>>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
>>> sum(map(len, d.values()))
7
回答by Jeffrey
I was looking for an answer to this when I found this topic untill I realized I already had something in my code to use this for. This is what I came up with:
当我找到这个主题时,我一直在寻找这个问题的答案,直到我意识到我的代码中已经有一些东西可以使用它。这就是我想出的:
count = 0
for key, values in dictionary.items():
count = len(values)
If you want to save the count for every dictionary item you could create a new dictionary to save the count for each key.
如果您想保存每个字典项的计数,您可以创建一个新字典来保存每个键的计数。
count = {}
for key, values in dictionary.items():
count[key] = len(values)
I couldn't exactly find from which version this method is available but I think .items method is only available in Python 3.
我无法确切地找到此方法可用的版本,但我认为 .items 方法仅在 Python 3 中可用。
回答by Rik Schoonbeek
Doing my homework on Treehouse I came up with this. It can be made simpler by one step at least (that I know of), but it might be easier for beginners (like myself) to onderstand this version.
在 Treehouse 做作业时,我想到了这个。至少可以简化一步(我知道),但对于初学者(如我自己)来说,理解这个版本可能更容易。
dict = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['bread', 'butter', 'tosti']}
total = 0
for value in dict:
value_list = dict[value]
count = len(value_list)
total += count
print(total)

