如何在不使用函数:dict、import、count、max、sort、enumerate、sorted的情况下提取列表的模式

2024-06-02 06:03:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

dict,import,count,max,sort,enumerate,sorted!

我不知道怎样才能写一个函数“count”和“sort”manuel。你知道吗


Tags: 函数import程序列表count模式数字sort
1条回答
网友
1楼 · 发布于 2024-06-02 06:03:27

使用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
网友
2楼 · 发布于 2024-06-02 06:03:27

如果对可以使用的函数或模块没有限制,那么获取列表模式的最有效方法是使用^{}类的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数据类型)来跟踪每个不同项的计数,然后遍历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

相关问题 更多 >