我确信这很愚蠢,但我根本无法绕过它。我有一个字典,像这样,每个键的值数量不等:
'John greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''],
'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''],
'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'],
'Lisa plowed ': ['field', 'field', '', '', '', ''],
我想知道每个键有多少个值,不是每个唯一值,而是每个键有多少个标记(重复与否)。所以我会得到这样的结果:
John greased 5
Paul alleged 5
Tracy freed 6
Lisa plowed 2
我试图用下面的代码来解决这个问题:
for key, value in sorted(result.items()):
print(key, len(value))
但是由于缺少值,所有长度都相同。 关于如何解决这个问题或在哪里找到它有什么想法吗?非常感谢您的帮助。
最佳答案
解决此问题的一种方法是更改最后一行:
print(key, len([item for item in value if item]))
所以你的完整代码:
ITEMS = {
'John greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''],
'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''],
'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'],
'Lisa plowed ': ['field', 'field', '', '', '', ''],
}
for key, value in ITEMS.items():
#print value
print(key, len([item for item in value if item]))
您还可以将filter
与bool
一起使用:
print(key, len(filter(bool, value)))
所以,循环:
for key, value in ITEMS.items():
#print value
print(key, len(filter(bool, value)))
您需要将 list
应用于 filter
,如下所示 print(key, len(list(filter(bool, value))))
在 Python 3 中。
关于python - 计算有多少值归因于 python (3.2) 字典的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843457/