【问题标题】:How to create and print a Dictionary that has keys as the names in list and their values as number of times the name appears on the list如何创建和打印一个字典,其中键作为列表中的名称,其值作为名称出现在列表中的次数
【发布时间】:2022-01-24 04:01:30
【问题描述】:

我有一个名字列表:

list = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']

使用这个列表,我创建了以下字典:

listA = {"G": "Ginger", "W": "Willow", "S": "Scout", "R": ["Roscoe", "Roscoe"], "B": ["Bear", "Baxter", "Bruno", "Boomer"], "K": "Kobe", "Z": ["Zara", "Ziggy"], "F": ["Fiona", "Fiona"], "M": "Milo", "O": ["Oakley", "Oakley"], "D": ["Dakota", "Dexter"], "P": ["Prince", "Panda"], "L": "Lucy", "E": ["Ella", "Emma"]}

打印字典中的键:

for key in listA.keys():
    print(key)

我明白了:

G
W
S
R
B
K
Z
F
M
O
D
P
L
E

如何获取每个名称在列表中出现的次数?

【问题讨论】:

  • 期望的结果是什么?尝试推导时有什么问题?
  • @enke 我期待以下结果。

标签: python list


【解决方案1】:

你不需要listA; collections.Counter 完全符合您的要求。

import collections
data = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']
counter = collections.Counter(data)

print(counter) # Prints counter object.
counter_as_dict = dict(counter) # Can be transformed into a dictionary using dict().
print(counter_as_dict.keys()) # Prints names in dictionary.

【讨论】:

  • 谢谢。它给了我这个输出: Counter({'Roscoe': 2, 'Fiona': 2, 'Oakley': 2, 'Ginger': 1, 'Willow': 1, 'Scout': 1, 'Bear': 1 , 'Kobe': 1, 'Baxter': 1, 'Zara': 1, 'Milo': 1, 'Dakota': 1, 'Prince': 1, 'Bruno': 1, 'Panda': 1, '德克斯特':1,'Ziggy':1,'露西':1,'Boomer':1,'Ella':1,'Emma':1})
  • 是的。您可以使用括号对其进行索引。如果你特别想要一本字典,你可以做dict(counter)。如果您希望解决有关此解决方案的其他问题,请在下面的评论中指定。
  • 如何使用 dict(counter)?如果我只想将键打印为列表中的名称?
  • 编辑成原始答案。
猜你喜欢
  • 2012-11-28
  • 1970-01-01
  • 2014-04-09
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多