检查第二个最大数量是否重复(python)

时间:2018-03-08 12:20:08

标签: python list max

我正在学习python,我想检查第二大数字是否在列表中重复。我尝试了几种方法,但我做不到。此外,我在谷歌上搜索了这个问题,我有几个答案从列表中获取/打印第二大数字,但我找不到任何答案来检查第二大数字是否重复。有人可以帮帮我吗?

以下是我的样本清单:

list1 = [5, 6, 9, 9, 11]
list2 = [8, 9, 13, 14, 14]

4 个答案:

答案 0 :(得分:4)

这是 1-liner

>>> list1 = [5, 6, 9, 9, 11]
>>> list1.count(sorted(list1)[-2]) > 1
True

或使用heapq

>>> import heapq
>>> list1 = [5, 6, 9, 9, 11]
>>> list1.count(heapq.nlargest(2, list1)[1]) > 1
True

答案 1 :(得分:0)

这是一个简单的算法:

  1. 使值唯一
  2. 按最大值排序列表
  3. 采取第二个元素
  4. 检查列表
  5. 中存在多少次此元素

    代码:

    list1 = [5, 6, 9, 9, 11]
    list2 = [8, 9, 13, 14, 14]
    
    def check(data):
        # 1. Make data unique
        unique = list(set(data))
        # 2. Sort by value
        sorted_data = sorted(unique, reverse=True)
        # 3. Takes the second element
        item = sorted_data[1]
        # 4. Check occurences
        if data.count(item) > 1:
            return True
        else:
            return False
    
    print(check(list1))
    print(check(list2))
    

    输出继电器

    True
    False
    

答案 2 :(得分:0)

带有collections.Counter

sorted提供了一种解决方案:

from collections import Counter

lst1 = [5, 6, 9, 9, 11]
lst2 = [8, 9, 13, 14, 14]

res1 = sorted(Counter(lst1).items(), key=lambda x: -x[0])[1]  # (9, 2)
res2 = sorted(Counter(lst2).items(), key=lambda x: -x[0])[1]  # (13, 1)

结果是第二大项目及其计数的元组。然后,检查项目是否重复是很简单的,例如, res1[1] > 1

答案 3 :(得分:0)

这是我的建议

li = [5, 6, 9, 9, 11]
li_uniq = list(set(li))               # list's elements are uniquified
li_uniq_sorted = sorted(li_uniq)      # sort in ascending order
second_largest = li_uniq_sorted[-2]   # get the 2nd largest -> 9
li.count(second_largest)              # -> 2 (duplicated if > 1)