[英]Most repeating element in list
I'm trying to make a function that finds the most repeating element in a list.我正在尝试创建一个函数来查找列表中重复次数最多的元素。 I thought to iterate through the list, check the count of each element and compare them(using 2 variables
numnum
and numnum2
)我想遍历列表,检查每个元素的计数并比较它们(使用 2 个变量
numnum
和numnum2
)
Something's wrong, it always prints 6.出了点问题,它总是打印 6。
l1 = [1, 5, 7, 7, 7, 7, 7, 7, 7, 7, 1, 3, 6, 6, 3, 4, 2, 6]
print(l1)
def mostrepeating(list1=None):
if list1 is None:
print('No list was received in the function.')
else:
numnum, numnum2, result = 0, 0, 0
for num in list1:
if list1.index(num) == 0:
numnum = list1.count(num)
result = num
else:
numnum2 = list1.count(num)
if numnum2 > numnum:
result = num
numnum = numnum2
print(result)
mostrepeating(l1)
The problem is with if list1.index(num) == 0
, it resets results
to 1, loosing the previous count.问题在于
if list1.index(num) == 0
,它将results
重置为 1,丢失先前的计数。 Remove it and set result
to the first item in the list.删除它并将
result
设置为列表中的第一项。 To reduce iterations you should also iterate over set
of the numbers为了减少迭代,您还应该迭代一
set
数字
def mostrepeating(list1=None):
if list1 is None:
print('No list was received in the function.')
else:
numnum, numnum2, result = 0, 0, 0
s = set(l1)
result = list1[0]
for num in s:
numnum2 = list1.count(num)
if numnum2 > numnum:
result = num
numnum = numnum2
print(result)
l1 = [1, 5, 7, 7, 7, 7, 7, 7, 7, 7, 1, 3, 6, 6, 3, 4, 2, 6,6,6,6,6,6,6,6,6,6,6,6,6]
appear_dict = {}
for n in l1:
appear_dict[n] = appear_dict.get(n, 0) + 1
most_repeat = l1[0]
for key, val in appear_dict.items():
most_repeat = key if val > most_repeat else most_repeat
print(most_repeat)
You can also use the Counter class from the collections module.您还可以使用集合模块中的Counter 类。
>>> l1 = [1, 5, 7, 7, 7, 7, 7, 7, 7, 7, 1, 3, 6, 6, 3, 4, 2, 6]
>>> from collections import Counter
>>> Counter(l1).most_common(1)[0][0]
7
You can use a function wich counts all numbers in a list and puts them in a dict.您可以使用一个函数来计算列表中的所有数字并将它们放入字典中。
Input:输入:
count_elements([1, 1, 1, 1, 3, 2, 5, 7, 8, 1])
count_elements([1, 1, 1, 1, 3, 2, 5, 7, 8, 1])
Output:输出:
{1: 5, 2: 1, 3: 1, 5: 1, 7: 1, 8: 1}
{1:5, 2:1, 3:1, 5:1, 7:1, 8:1}
Code:代码:
def add_element_to_dict(dictin, key):
dictout = dictin
if key in dictout.keys():
dictout[key] = dictout[key] + 1
else:
dictout[key] = 1
return dictout
def count_elements(list1=None):
if list1 == None:
print("No list specified")
return
else:
numbersdict = {}
for ele in list1:
numbersdict = add_element_to_dict(numbersdict, ele)
return numbersdict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.