lst = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
a = iter(lst)
c = (None, None)
while True:
try:
b = next(a)
count = 0
for i in lst:
if b == i:
count += 1
if c[0] == None:
c = (count, b)
elif count > c[0]:
c = (count, b)
except StopIteration:
break
print(c[1])
# 3
def get_mode(lst):
dic = {}
for item in lst:
dic[item] = dic.get(item, 0) + 1
mode, largest = None, None
for item, count in dic.items():
if largest is None or largest < count:
mode, largest = item, count
return mode
使用
c
作为保存(count, item)
的元组。我们可以使用iter
遍历lst
中的值,如果它们的计数大于上一个值,我们可以更新元组来表示该项,在iter
用完之后,我们从元组打印该项。你知道吗如果对可以使用的函数或模块没有限制,那么获取列表模式的最有效方法是使用^{} 类的
most_common
方法:但是,由于不允许使用
import
,因此可以使用dict(不是dict
函数,而是dict数据类型)来跟踪每个不同项的计数,然后遍历dict项以找到计数最大的项:以便:
将返回:
2
相关问题 更多 >
编程相关推荐