【问题标题】:Python program to sort and count repeated no in list [closed]Python程序对列表中重复的no进行排序和计数[关闭]
【发布时间】:2018-03-04 08:25:52
【问题描述】:

编写一个 Python 函数 histogram(l),它将一个具有重复的整数列表作为输入,并返回一个对列表,如下所示: 对于 l 中出现的每个数字 n,函数返回的列表中应该恰好有一对 (n,r),其中 r 是 n 在 l 中的重复次数。

最终列表应按 r(重复次数)升序排序。对于重复次数相同的数字,按数字值的升序排列。

例如:

>>> histogram([13,12,11,13,14,13,7,7,13,14,12])
[(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]

>>> histogram([7,12,11,13,7,11,13,14,12])
[(14, 1), (7, 2), (11, 2), (12, 2), (13, 2)]

>>> histogram([13,7,12,7,11,13,14,13,7,11,13,14,12,14,14,7])
[(11, 2), (12, 2), (7, 4), (13, 4), (14, 4)]

【问题讨论】:

  • 致所有回答此问题的人:请您考虑询问 OP 他尝试了什么,然后帮助他找到适当的解决方案。因为这看起来像是一道作业题。

标签: python list function sorting


【解决方案1】:

Counter 对象非常适合这个。

>>> from collections import Counter
>>> Counter([13,12,11,13,14,13,7,7,13,14,12])
Counter({13: 4, 12: 2, 14: 2, 7: 2, 11: 1})

编辑: 如果您希望将结果放在按值排序的元组列表中,您可以执行以下操作。

>>> count = Counter([13,12,11,13,14,13,7,7,13,14,12])
>>> sorted(count.items(), key=lambda c: c[1])
[(11, 1), (12, 2), (14, 2), (7, 2), (13, 4)]

【讨论】:

    【解决方案2】:

    下次请分享你自己的尝试。

    def make_histogram(lst):
        new_lst = list(set([(i, lst.count(i)) for i in lst]))
        new_lst.sort(key=lambda x: x[1])
        return new_lst
    

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2021-03-17
      相关资源
      最近更新 更多