循环遍历除其

2024-09-28 21:52:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在列表中查找出现次数最多的项。在

为此,我尝试将列表中的每个项目与列表中的所有其他项目进行比较,并在每次找到匹配项时将count的值增加1。在

def findInt(array):
    count = []
    count = [1 for i in range(0,len(array))]        
    for i,item in enumerate(array):
        if (array[i] == array[i:]):  #How can I compare it with all items except itself?
            count[i]+=1

    return max(count), count.index(max(count))


findInt(array=[1,2,3])

我的问题是“如何将该项目与除自身之外的所有其他项目进行比较”?在


Tags: 项目in列表forlendefcountrange
3条回答

虽然有很多更好的方法来解决这个问题,例如@zwer对您的问题的评论中指出的,但我将如何解决您的问题:

# O(n ** 2)
def find_int(array):
    n = len(array)
    count = [1 for i in range(n)]

    for i in range(n):
        for j in range(n):
            if i == j: continue

            if array[i] == array[j]:
                count[i] += 1

    return max(count), count.index(max(count))

# Worse than O(n ** 2)
def find_int_using_slice(array):
    n = len(array)
    count = [1 for i in range(n)]

    for i in range(n):
        for a_j in array[0:i] + array[i+1:]:
            if array[i] == a_j:
                count[i] += 1

    return max(count), count.index(max(count))

print(find_int_using_slice([1,2,3,1,2,3,2]))

我们在这里使用嵌套的for循环,并使用continue在两个索引相同时跳过迭代。在

除非专门用于学习目的,否则请考虑将内置功能用于常见任务,因为它们已得到很好的实施、测试、优化等

有许多潜在的解决方案,但根据应用程序的要求,我推荐两种方法:1)从左到右一次排序和计数:O(n*log(n))并失去原来的顺序;或者2)使用字典来维护计数,只需要从左到右进行一次循环:O(n),但使用更多的内存。当然,更好的选择是使用高度优化的内置方法,但这是你的选择

更新了答案以反映操作不想使用collections.Counter

使用setdefault为第一次出现的计数器初始化,然后递增计数器。然后可以使用max和一个键来查找最常见的项。在

def most_common(ar):
    y = {}

    for item in ar:
        y.setdefault(item, 0)
        y[item] += 1

    return max(y.items(), key=lambda x: x[1])

array = [1, 2, 1, 1, 2, 1, 3, 3, 1]
most_common(array)

(1, 5)  # (Most common item, occurrences of item)

使用具有most_common函数的collections.Counter。在

import collections
def findInt(array):
    c = collections.Counter(array)
    return c.most_common(1)

演示

^{pr2}$

医生

class collections.Counter([iterable-or-mapping])
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

most_common([n])
Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

相关问题 更多 >