[英]Why is my code not checking every value in list?
我试图检查某个值连续重复多少次,但我遇到了一个问题,我的代码在没有检查的情况下留下了最后一个数字。
Ai = input()
arr = [int(x) for x in Ai.split()]
c = 0
frozen_num = arr[0]
for i in range(0,len(arr)):
print(arr)
if frozen_num == arr[0]:
arr.remove(arr[0])
c+=1
else:
frozen_num = arr[0]
print(c)
所以假设我输入:1 1 1 1 5 5 我的代码将给出输出 5 而不是 6
我希望你明白我在说什么。 我对 python 很陌生,而且这段代码还没有完成,后面的数字将被附加,所以我得到输出:[4, 2] 因为“1”重复 4 次,“5”重复 2 次。
编辑 - 我不小心写了 6 和 7 而不是 5 和 6。
您可以使用Collections
模块的Counter
来测量不同数字的所有出现。
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]
如果你想坚持你的方法而不使用外部库,你可以添加一个 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.