【问题标题】:How to turn Counter results to a list of tuples [duplicate]如何将计数器结果转换为元组列表[重复]
【发布时间】:2019-03-11 12:50:37
【问题描述】:
example = ['apple', 'pear', 'apple']

我怎样才能从上面得到下面的

result = [(apple ,2), (pear, 1)]

我只知道怎么用Counter,但是不知道怎么把结果转成上面的格式。

元组命令不起作用:

>>> tuple(Counter(example))
('apple', 'pear')

【问题讨论】:

    标签: python python-3.x dictionary tuples counter


    【解决方案1】:

    您可以拨打listCounter.items

    from collections import Counter
    
    result = list(Counter(example).items())
    
    [('apple', 2), ('pear', 1)]
    

    dict.items 给出了一个可迭代的键值对。作为dict 的子类,Counter 也是如此。因此,在可迭代对象上调用 list 将为您提供一个元组列表。

    上面给出了 Python 3.6+ 中的项目插入排序。要按降序排列,请使用Counter(example).most_common(),它会返回一个元组列表。

    【讨论】:

    • 或者对于排序结果(按计数)作为单个调用,Counter(example).most_common() 将所有工作作为单个调用完成。
    【解决方案2】:

    只要做:

    Counter(example).items()
    

    这不是一个列表,但如果想要一个列表:

    list(Counter(example).items())
    

    因为Counter本质上是一个dict,具有和dict等价的功能,所以Counter就有items

    唯一的问题是Counter有一个elementsmost_commonmost_common实际上可以解决这个问题),elementsCounter转换为itertools.chain对象然后make to list将是原始列表但按出现次数排序。

    most_common 示例:

    Counter(example).most_common()
    

    不需要转换为列表,它已经是一个列表,但它按出现次数排序(意味着最大 --- 到 --- 最小)。

    两个输出:

    [('apple', 2), ('pear', 1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2017-09-10
      • 2016-01-29
      • 2017-12-30
      • 1970-01-01
      相关资源
      最近更新 更多