【问题标题】:Counting Lists and Adding to a new Dictionary (Python)计数列表并添加到新字典(Python)
【发布时间】:2019-10-30 11:40:21
【问题描述】:

我正在使用字典,想知道如何输出一个字典,其中键是给定字典中出现的单词,值是它在该字典中出现的次数。

比如说,

A = {'#1': ['Yellow', 'Blue', 'Red'], '#2': ['White', 'Purple', 'Purple', 'Red']}
B - []
for key in A:
    B.append(A[key])

>>> B
>>> [['Yellow', 'Blue', 'Red'], ['White', 'Purple', 'Purple', 'Red']]

在返回键的相应值后,我现在可以遍历每个字符串列表并展平值列表。

C = []
for sublist in B:
    for item in sublist:
        C.append(item)

我知道我需要计算某些字符串在该列表中出现的次数,然后填充字典,其中键是颜色,值是它出现的次数。这部分主要是我遇到困难的地方。

【问题讨论】:

标签: python dictionary dictionary-comprehension


【解决方案1】:

您可以使用Counter 对象:

>>> from collections import Counter
>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']
>>> Counter(c)
Counter({'Red': 2, 'Purple': 2, 'Yellow': 1, 'Blue': 1, 'White': 1})

或者自己制作:

>>> d = {i: c.count(i) for i in c}
>>> d
{'Yellow': 1, 'Blue': 1, 'Red': 2, 'White': 1, 'Purple': 2}

您还可以缩短您的 c 创建时间:

c = []
for i in A.values():
    c.extend(i)

>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']

或:

c = [j for i in A.values() for j in i]

>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多