Python For循环,用于列出列表中的数字计数

2024-09-29 20:32:03 发布

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

我有一个没有特定顺序的随机数列表。有没有办法计算每个数字在列表中出现的次数,并使用for循环创建一个包含这些计数的新列表?因此,不要使用现有的Python函数。 例如,我有一个列表[9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]。 我想要的输出是[2,2,3,2,4等]

我目前拥有的代码是:

def countlisting(numberlist):
    the_count = 0
    q = 0
    listofcount = []
    for i in range(len(numberlist)):
        if numberlist[i] == numberlist[q]:
            the_count += 1
            listofcount.append(the_count)
            q += 1
    return listofcount

the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
print(countlisting(the_numberlist))  


Tags: the函数代码列表for顺序defcount
3条回答
sum=0
list1=[]
the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
for i in range(len(the_numberlist)):
    for j in range(len(the_numberlist)):
        if the_numberlist[0]==the_numberlist[j]:
         sum+=1
    if len(the_numberlist)!=0:
      remove_element=the_numberlist[0]
    else:
        break
    while remove_element in the_numberlist:
        the_numberlist.remove(remove_element)
    list1.append(sum)
    sum=0
print(list1)

#输出:[2,2,3,4,2,1,1,1,2,1,1]

我尽了最大努力不要使用这个函数

祝你好运

您可以使用^{}并从dict获取值,如下所示:

>>> from collections import Counter
>>> the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
>>> list(Counter(the_numberlist).values())
[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]



# for more explanation
>>> Counter(the_numberlist)
Counter({9: 2,
         18: 2,
         13: 3,
         6: 4,
         16: 2,
         17: 1,
         10: 1,
         15: 1,
         11: 2,
         8: 1,
         20: 1})

您可以自己实现这个计数器

>>> dct_cnt = {}
>>> for num in the_numberlist:
...    dct_cnt[num] = dct_cnt.get(num, 0) + 1
    
>>> dct_cnt
{9: 2, 18: 2, 13: 3, 6: 4, 16: 2, 17: 1, 10: 1, 15: 1, 11: 2, 8: 1, 20: 1}

>>> list(dct_cnt.values())
[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]

您可以使用^{}进行以下操作:

from collections import Counter

the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
c = Counter(the_numberlist)
print(list(c.values()))

输出:

[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]

相关问题 更多 >

    热门问题