我堆了一会儿。我试过调试,但我找不到解决方案。我试图按升序计算数字的出现次数 例如,我有这些输入:2 5 6 5 4 3 23 43 2 我得到的输出 -2发生2次 -3发生一次 -4次发生一次 -5次发生2次 -6发生一次 -43发生一次#为什么会发生这种情况? 23次出现
def main():
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)
for key, value in count.items():
if value == 1:
print('{} occurs one time'.format(key))
else:
print('{} occurs {} times'.format(key, value))
main()
答案 0 :(得分:1)
输出正确:
输入:
Country
输出:
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))