【问题标题】:Count values with items in a dictionary with sublists计算带有子列表的字典中的项目的值
【发布时间】: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


【解决方案1】:

要结合这两个解决方案,只需将第一个解决方案中的 Counter(v) 替换为第二个解决方案即可。

from collections import Counter

d = {'a': [['I', 'said', 'that'], ['said', 'I']],
     'b': [['she', 'is'], ['he', 'was']]}


counts = {k: Counter(word
                     for sublist in lst
                     for word in sublist)
          for k, lst in d.items()}

print(counts)

输出:

{'a': Counter({'I': 2, 'said': 2, 'that': 1}),
 'b': Counter({'she': 1, 'is': 1, 'he': 1, 'was': 1})}

【讨论】:

  • 嗨,谢谢。这就是我一直在寻找的。​​span>
【解决方案2】:

您可以合并您的子列表以获得您的 d2:d2 = {k: reduce(list.__add__, d[k], []) for k in d}

在python3中,你需要from functools import reduce

【讨论】:

    【解决方案3】:

    为此使用itertoolscollections 模块。使用itertools.chain 展平嵌套列表并使用collections.Counter 计数

    import itertools, collections
    d = {
             'a': [['I', 'said', 'that'], ['said', 'I']],
             'b':[['she', 'is'], ['he', 'was']]
        }
    out_dict = {}
    for d_key, data in d.items():    
        counter = collections.Counter(itertools.chain(*data))
        out_dict[d_key] = counter
    print out_dict
    

    输出:

    {'a': Counter({'I': 2, 'said': 2, 'that': 1}),
     'b': Counter({'she': 1, 'is': 1, 'he': 1, 'was': 1})}
    

    【讨论】:

    • 在使用 print 语句时实际粘贴输出总是好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2011-03-30
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多