【问题标题】:Count occurrences of an element in list计算列表中某个元素的出现次数
【发布时间】:2017-10-05 07:48:41
【问题描述】:

我知道已经有很多关于这个特定主题的问题,但我找不到适合我的问题的解决方案。

我有输入:

2, 20, 15, 16, 17, 3, 8, 10, 7

我想看看我的代码中是否有“双”数字。我试过使用这段代码。

lijst = input('Give a list:  ')
teller = 0
for i in lijst.split(','):
    if lijst.count(i) != 1:
        teller += 1
print(teller != 0)

通常我应该得到 False,因为给定列表中没有双数。但是,我收到 True。我建议这是因为 2 也出现在 20 中。

True

有谁知道如何避免这个问题,所以“2”不计算两次?

【问题讨论】:

    标签: python list counter


    【解决方案1】:

    您可以使用collections.Counter,它正是这样做的

    >>> data = [2, 20, 15, 16, 17, 3, 8, 10, 7]
    >>> from collections import Counter
    >>> Counter(data)
    Counter({2: 1, 3: 1, 7: 1, 8: 1, 10: 1, 15: 1, 16: 1, 17: 1, 20: 1})
    >>> 
    

    统计出现次数,返回一个dict,key表示item,value表示出现次数。

    如果您只需要知道是否有重复项,无论哪个项目是重复项,您都可以简单地在列表上使用Set,然后检查len()

    len(data) == len(set(data))

    【讨论】:

      【解决方案2】:

      您可以将输入的长度与输入中唯一元素集的长度进行比较:

      def has_repeated_elements(input):
          """returns True if input has repeated elements,
          False otherwise"""
          return len(set(input)) != len(input)
      
      print(not has_repeated_elements(input))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 2020-06-09
        • 1970-01-01
        • 2011-08-10
        • 1970-01-01
        相关资源
        最近更新 更多