我正在尝试在列表中查找出现次数最多的项。在
为此,我尝试将列表中的每个项目与列表中的所有其他项目进行比较,并在每次找到匹配项时将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])
我的问题是“如何将该项目与除自身之外的所有其他项目进行比较”?在
虽然有很多更好的方法来解决这个问题,例如@zwer对您的问题的评论中指出的,但我将如何解决您的问题:
我们在这里使用嵌套的for循环,并使用
continue
在两个索引相同时跳过迭代。在除非专门用于学习目的,否则请考虑将内置功能用于常见任务,因为它们已得到很好的实施、测试、优化等
有许多潜在的解决方案,但根据应用程序的要求,我推荐两种方法:1)从左到右一次排序和计数:O(n*log(n))并失去原来的顺序;或者2)使用字典来维护计数,只需要从左到右进行一次循环:O(n),但使用更多的内存。当然,更好的选择是使用高度优化的内置方法,但这是你的选择
更新了答案以反映操作不想使用
collections.Counter
使用
setdefault
为第一次出现的计数器初始化,然后递增计数器。然后可以使用max
和一个键来查找最常见的项。在使用具有most_common函数的collections.Counter。在
演示
^{pr2}$医生
相关问题 更多 >
编程相关推荐