我有一个没有特定顺序的随机数列表。有没有办法计算每个数字在列表中出现的次数,并使用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))
#输出:[2,2,3,4,2,1,1,1,2,1,1]
我尽了最大努力不要使用这个函数
祝你好运
您可以使用^{} 并从
dict
获取值,如下所示:您可以自己实现这个计数器
您可以使用^{} 进行以下操作:
输出:
相关问题 更多 >
编程相关推荐