问题描述
输入:第一行输入M和N两个数。
第二行含有M个数以空格分隔
输出:统计输出在M个数中1-N的数的数量。如下图1有5个,2有2个,3有3个。
例:
代码
方法一
lineInput1=list(map(int,input().split()))
count={}
for i in range(1,lineInput1[1]+1):
count[str(i)]=0
lineInput2=input()
for character in lineInput2:
if character in count.keys():
count[character] = count[character]+1
print(*count.values())
要注意列表键的属性是字符串还是整形。类型错误无法正确运算。
列表元组字典前加*
方法二
howmany, to = map(int, input().split(' '))
array = list(map(int, input().split(' ')))
counters = []
while to != 0:
counters.append(str(array.count(to)))
to -= 1
counters.reverse()
print(' '.join(counters))
这个方法自定义了count函数,其中while无限循环这个不等于的用法很有学习价值,并用了reverse方法。