2 回答
![?](http://img1.sycdn.imooc.com/545869510001a20b02200220-100-100.jpg)
TA贡献1804条经验 获得超7个赞
您可以使用该Counter模块Collections的 来测量不同数字的所有出现次数。
from collections import Counter
arr = list(Counter(input().split()).values())
print(arr)
输入为的输出1 1 1 1 5 5:
1 1 1 1 5 5
[4, 2]
![?](http://img1.sycdn.imooc.com/533e4ce900010ae802000200-100-100.jpg)
TA贡献1818条经验 获得超11个赞
如果您想坚持使用您的方法而不使用外部库,您可以添加一个 if 语句来检测何时到达数组的最后一个元素,并以与其他元素不同的方式处理它:
Ai=input()
arr = [int(x) for x in Ai.split()]
L=[]
c = 0
frozen_num = arr[0]
for i in range(0, len(arr)+1):
print(arr)
if len(arr)==1: #If we reached the end of the array
if frozen_num == arr[0]: #if the last element of arr is the same as the previous one
c+=1
L.append(c)
else: #if the last element is different, just append 1 to the end of the list
L.append(c)
L.append(1)
elif frozen_num == arr[0]:
arr.remove(arr[0])
c += 1
else:
L.append(c)
c=0
frozen_num = arr[0]
print(L)
输入
[5,5,5,6,6,1]
输出
[3,2,1]
添加回答
举报