如何在不使用以下函数的情况下给出列表的模式:字典、导入、计数、最大值、排序、枚举、排序



我必须编写一个程序,其中我输入了 10 个数字,并且程序必须给出列表的模式,而无需取消函数:

字典,导入,计数,最大值,排序,枚举,排序!

我不知道我如何编写函数"计数"一个"排序"曼努埃尔。

使用c作为保存(count, item)元组。我们可以使用iter遍历lst中的值,如果它们的计数大于前一个,我们可以更新元组以表示该项目,在iter用完后,我们从元组中打印项目。

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

如果对可以使用的函数或模块没有限制,则获取列表模式的最有效方法是使用collections.Counter类的most_common方法:

from collections import Counter
Counter([1,1,2,2,2,3,4,4,5,6]).most_common(1)[0][0] # this returns 2

但是由于不允许使用import,您可以自己实现相同的逻辑,方法是使用 dict(不是dict函数,而是 dict 数据类型(来跟踪每个不同项的计数,然后遍历字典项以查找计数最大的项:

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

因此:

get_mode([1,1,2,2,2,3,4,4,5,6])

会返回:2

最新更新