【问题标题】:Using fromkeys to create a dictionary使用 fromkeys 创建字典
【发布时间】:2017-05-03 14:26:19
【问题描述】:

我正在用 Python 编写代码

我有一个名为“位置”的元组列表。其中一些元组在“位置”中出现超过 1 次。我想用代码创建一个名为 d 的字典:

d["positions"] = dict.fromkeys(positions)

这给了我一个预期的字典,每个键的每个值都等于 None。但现在我希望这些值等于元组在“位置”中出现的次数。这是否可能无需遍历列表“位置”或不使用诸如位置.count(x)之类的东西?

亚历克斯

【问题讨论】:

  • 听起来你想要collections.Counter()
  • 你能把那本词典贴出来吗?

标签: python list dictionary find-occurrences fromkeys


【解决方案1】:
import collections


lt = [ (1,2) , (2,3) , (2,3) , (4,5) , (1,2)]

counter = collections.Counter()
counter.update(lt)
print(dict(counter))

结果

{(1, 2): 2, (2, 3): 2, (4, 5): 1}

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 2020-10-25
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多