【问题标题】:how can I manipulate key with for loops to update dictionary如何使用 for 循环操作键来更新字典
【发布时间】:2018-04-09 21:43:56
【问题描述】:

我正在尝试将列表放入字典并计算列表中每个单词的出现次数。我不明白的唯一问题是,当我使用更新函数时,它将 x 作为字典键,当我希望 x 成为 list_ 的 x 值时。我是 python 新手,所以任何建议都值得赞赏。谢谢

list_ = ["hello", "there", "friend", "hello"]
d = {}
for x in list_:
    d.update(x = list_.count(x))

【问题讨论】:

    标签: python list dictionary for-loop key


    【解决方案1】:

    如果您想要一种将项目列表转换为包含list_entry: number_of_occurences 映射的字典的简单方法,请使用Counter 对象。

    >>> from collections import Counter
    >>> words = ['hello', 'there', 'friend', 'hello']
    >>> c = Counter(words)
    
    >>> print(c)
    Counter({'hello': 2, 'there': 1, 'friend': 1})
    
    >>> print(dict(c))
    {'there': 1, 'hello': 2, 'friend': 1}
    

    【讨论】:

    • 哇不知道你能做到这一点。谢谢!
    【解决方案2】:

    一个选项是使用带有list.count() 的字典理解,如下所示:

    list_ = ["hello", "there", "friend", "hello"]
    d = {item: list_.count(item) for item in list_}
    

    输出:

    >>> d
    {'hello': 2, 'there': 1, 'friend': 1}
    

    但最好的选择应该是@AK47 的解决方案中使用的collections.Counter()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-03
      • 2019-02-03
      • 2021-05-13
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多