简体   繁体   English

使用count()计算列表中某事物出现的次数

[英]Using count() to count the amount of times something appears in a list

Well, firstly, hi there. 好吧,首先,你好。 I don't believe this has appeared yet, so correct me if it has. 我不认为这已经出现,所以请纠正我。

I am creating a dice rolling simulator that returns the frequency of the numbers rolled as well as the numbers rolled. 我正在创建一个掷骰子模拟器,该模拟器返回掷骰子的频率以及掷骰子的频率。 You can input the amount of sides and amount of rolls. 您可以输入边数和卷数。 Good starter project, so I've been told. 好的入门项目,所以有人告诉我。 I'm using count() to count the amount of times each number appears on the list. 我正在使用count()来计算每个数字出现在列表中的次数。

That's where it gets a bit off.The highest value in the list has one less than it should, for example: 这就是问题所在,列表中的最高值比应有的数值少一个,例如:

You have a 6 sided die, and you roll it 6 times. 您有一个6面的骰子,然后滚动6次。 You get 1, 2, 3, 4, 5 and 6. When it displays occurrences it would display all but the highest value as 1. It says that six appears 0 times. 您得到1、2、3、4、5和6。当显示出现时,它将显示除最高值以外的所有值,即1。它表示六个出现0次。

Here's the code slab: 这是代码板:

    a.sort()
    topvalue = a.pop()
    while topvalue >= 0:
        y = a.count(topvalue)
        print topvalue, "appears", y< "times."
        topvalue = topvalue-1
        if topvalue == -1:
            break

Going back to my example, due to the way this was coded, if six truly didn't appear, it wouldn't even be printed, but it is. 回到我的示例,由于编码方式的原因,如果没有真正出现六个,则甚至不会打印出来,但是可以打印出来。 Hope you and your python wisdom can help! 希望您和您的python智慧能有所帮助!

To get the last element here, instead of: 在这里获取最后一个元素,而不是:

topvalue = a.pop()

do: 做:

topvalue = a[-1]  # This represents the last index.

This is because pop() actually removes the last element, hence the one-off error. 这是因为pop()实际上删除了最后一个元素,因此出现了一次性错误。


Although as an idea, in your position I would do: 尽管是一个主意,但您可以:

from collections import Counter

amounts = Counter(a)
for item, num in amounts.items():
    print('{0} occurred {1} times'.format(item, num))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM