Python 3.x 数一数

Python 3.x 数一数,python-3.x,Python 3.x,我累了一会儿。我试着调试,但我想不出解决办法。我试图按升序数数数字的出现次数 例如,我有这些输入:2 5 6 5 4 3 23 43 2 我得到的输出 -2发生2次 -3发生一次 -4发生一次 -5发生2次 -6发生一次 -43只发生一次#为什么会发生这种情况? 23发生一次 def main(): main()输出正确: 输入: 2 5 6 5 4 3 23 43 2 输出: Enter integers between 1 and 100:-2 5 6 5 4 3 23 43 2 2 oc

我累了一会儿。我试着调试,但我想不出解决办法。我试图按升序数数数字的出现次数 例如,我有这些输入:2 5 6 5 4 3 23 43 2 我得到的输出 -2发生2次 -3发生一次 -4发生一次 -5发生2次 -6发生一次 -43只发生一次#为什么会发生这种情况? 23发生一次

def main():

main()

输出正确:

输入:

2 5 6 5 4 3 23 43 2
输出:

Enter integers between 1 and 100:-2 5 6 5 4 3 23 43 2
2 occurs 2 times
3 occurs one time
4 occurs one time
5 occurs 2 times
6 occurs one time
43 occurs one time
23 occurs one time
必须按键对字典进行排序以获得所需的输出:

import collections
while True:
    try:
        numbers = input("Enter integers between 1 and 100:-")
        #my_list= [int(x) for x in input().split(' ')]
        my_list = list(map(int, numbers.strip().split(' ')))

        break
    except ValueError:
        print ("Oops ! enter an integer... ")
count = {}

for x in set(my_list):
    count[x] = my_list.count(x)
count = collections.OrderedDict(sorted(count.items()))
for key, value in count.items():
    if value == 1:
        print('{} occurs one time'.format(key))
    else:
        print('{} occurs {} times'.format(key, value))
以下是输出:

Enter integers between 1 and 100:-23 23 1 2 3 4 5 2 2 4 2 55 55 5 5 55 55 55 55
1 occurs one time
2 occurs 4 times
3 occurs one time
4 occurs 2 times
5 occurs 3 times
23 occurs 2 times
55 occurs 6 times

这对我来说很好代码似乎很好阅读它是一本专门的字典,如果你给它一个iterable,它可以自己完成计数部分。错误的输出可能源于没有将代码复制到这个问题中,并且在输出字符串前面使用了一个字面值“-”……当显示发生率时,它应该按升序排列你的意思是43,23,6,5,4,3,2?我的意思是2 3 4 5 6 23 43和上面的每个数字发生更新代码,需要按键对字典进行排序,以实现所需的输出。但我也觉得奇怪为什么23总是在结尾
Enter integers between 1 and 100:-23 23 1 2 3 4 5 2 2 4 2 55 55 5 5 55 55 55 55
1 occurs one time
2 occurs 4 times
3 occurs one time
4 occurs 2 times
5 occurs 3 times
23 occurs 2 times
55 occurs 6 times