【问题标题】:How to create a dictionary with values representing the amount of times a word is repeated in a list?如何创建一个字典,其值表示一个单词在列表中重复的次数?
【发布时间】:2018-05-16 20:19:29
【问题描述】:
x = ["hi", "hi", "bye", "see", "you", "later"]  
for i in x:  
    sum = x.count(i)    
    y = dict((i, sum) for i in x)  
print(y)

当我打印此代码时,它给了我一个键值为 1 的字典。但是,我想要实现的是字典中的值是列表中每个单词重复的次数。所以,对于这个例子: {'hi':2, 'bye':1, 'see':1, 'you':1, 'later':1} 是我在给定输入的情况下试图实现的输出X。谁能帮我?谢谢:)

【问题讨论】:

标签: python-3.x list dictionary


【解决方案1】:

defaultdict 适合这种任务。

from collections import defaultdict
x = ["hi", "hi", "bye", "see", "you", "later"]  

y = defaultdict(int)
for key in x:
    y[key] += 1
print(y)
print(dict(y))

添加计数器版本。就像在 cmets 中一样(比 defaultdict 容易得多)。

from collections import Counter
x = ["hi", "hi", "bye", "see", "you", "later"]  
y = Counter(x)
print(y)

添加而不导入模块。

x = ["hi", "hi", "bye", "see", "you", "later"]  

y = dict()
for key in x:
    if not key in y:
        # y.update({key: 1})
        y[key] = 1
    else:
        y[key] += 1

print(y)

【讨论】:

  • 有没有办法在不导入任何模块的情况下做到这一点?
【解决方案2】:

你可以有这样的东西

x = ["hi", "hi", "bye", "see", "you", "later"]  
y = {i:x.count(i) for i in x}
print(y)

结果将是

{'bye': 1, 'hi': 2, 'later': 1, 'see': 1, 'you': 1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2016-07-01
    • 2016-10-05
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    相关资源
    最近更新 更多