2 回答

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]

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]
添加回答
舉報