我正在尝试创建一个在列表中找到最重复元素的函数。我想遍历列表,检查每个元素的计数并进行比较(使用2个变量numnum
和numnum2
)
出了点问题,它总是打印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)
问题来源:stackoverflow
问题在于if list1.index(num)== 0
,它将results
重置为1,失去了先前的计数。删除它,并将result
设置为列表中的第一项。为了减少迭代,您还应该迭代数字的“设置”
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)
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。