【发布时间】:2018-06-19 19:49:08
【问题描述】:
有人警告我,这个问题经常被否决,但我还没有看到针对我的特定问题的解决方案。
我有一本像这样的字典:
d = {'a': [['I', 'said', 'that'], ['said', 'I']],
'b':[['she', 'is'], ['he', 'was']]}
我希望输出是一个带有原始键的字典,然后是一个包含一个值的字典,该值指示每个单词的计数(例如,{'a':{'I':2, 'said':2, 'that':1} 等等 b。
如果值在列表而不是子列表中,我可以通过使用 Counter 获得我想要的:
d2 = {'a': ['I','said','that', 'I'],'b': ['she','was','here']}
from collections import Counter
counts = {k: Counter(v) for k, v in d2.items()}
但是,我得到了TypeError: unhashable type: 'list',因为包含我要计算的值的列表是子列表,并且包含它们的列表不可散列。
我也知道,如果我只有子列表,我可以通过以下方式得到我想要的:
lst = [['I', 'said', 'that'], ['said', 'I']]
Counter(word for sublist in lst for word in sublist)
但我就是不知道如何结合这些想法来解决我的问题(我想它在于将这两者结合起来)。
我试过了
for key, values in d.items():
flat_list = [item for sublist in values for item in sublist]
new_dict = {key: flat_list}
counts = {k: Counter(v) for k, v in new_dict.items()}
但这只会给我第二个列表的计数(因为 flat_list 本身只返回第二个键的值。
【问题讨论】:
-
可以有子列表还是只有
lists -
它不会是列表。键的值将是字典。
标签: python list dictionary counter