代码之家  ›  专栏  ›  技术社区  ›  Delowar Hosain

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

  •  -1
  • Delowar Hosain  · 技术社区  · 7 年前

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

    以下是我的示例列表:

    list1 = [5, 6, 9, 9, 11]
    list2 = [8, 9, 13, 14, 14]
    
    4 回复  |  直到 7 年前
        1
  •  4
  •   Austin    7 年前

    这是一个 1-衬里 :

    >>> 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
    
        2
  •  0
  •   Arount    7 年前

    这是一个简单的算法:

    1. 使值唯一
    2. 按最大值对列表排序
    3. 取第二个元素
    4. 检查此元素在列表中出现的次数

    代码:

    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
    
        3
  •  0
  •   jpp    7 年前

    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

        4
  •  0
  •   Jal    7 年前

    这是我的建议

    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)