【问题标题】:Find the frequency of a word in list with accordance to the first indexed item根据第一个索引项查找列表中单词的频率
【发布时间】:2019-06-06 10:14:25
【问题描述】:

假设我有一个这样的列表

my_list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'), 
  (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]

现在我想在 python 3 中编写一个代码,以便它根据第一个项目返回项目第二个元素的频率。 例如,我希望输出打印如下内容:

1: 3 (A), 1 : 1 (B), 20: 2(BB), 100: 3(CC)

抱歉英语不好。任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x list numpy


    【解决方案1】:

    使用 Collections 模块中的 Counter 方法。

    from collections import Counter
    my_list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'), 
      (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]
    print(Counter(my_list))
    

    输出:

    Counter({(1, 'A'): 3, (100, 'CC'): 3, (20, 'BB'): 2, (1, 'B'): 1})
    

    【讨论】:

    • 我不知道为什么,但是当我尝试使用 Counter 作为您的建议时,我收到了这个错误 _count_elements(self, iterable) TypeError: unhashable type: 'writeable void-scalar
    • 你能告诉我你提供了什么输入吗?
    • 计数器不适用于非散列类型,例如颜色 = [['red', 'warm'], ['blue', 'cold'], ['red', 'warm ']]。
    • 我想通了 tbanks
    【解决方案2】:

    您也可以使用 Dict 来实现此目的,而不是导入集合。由于列表中的项目是元组,因此它们可以用作字典的键。

    您可以这样做:

    list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'),  (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]
    
    dict = {}
    
    for item in list:
        if item in dict:
            dict[item] += 1
        else:
            dict[item] = 1
    print(dict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 2012-01-10
      相关资源
      最近更新 更多