我肯定这很傻,但我就是绕不过去。我有一个字典,像这样,每个键的值的数目不相等:
'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))
但是由于缺少值,所有的长度都是一样的。 有什么办法解决这个问题或者在哪里找到答案吗?非常感谢你的帮助。
将^{} 与
None
一起使用,它将从传递给它的iterable中筛选出所有错误值。在Python3中,
filter
返回一个迭代器,因此您应该对它调用list()
代码:
filter(None,..)
与列表理解的时间比较:解决这个问题的一种方法是,更改最后一行:
所以你的完整代码:
也可以将
filter
与bool
一起使用:所以,循环:
您需要像Python 3中的
print(key, len(list(filter(bool, value))))
那样,在filter
上应用list
。看看这个:
相关问题 更多 >
编程相关推荐