简体   繁体   English

为什么我的代码没有检查列表中的每个值?

[英]Why is my code not checking every value in list?

I'm trying to check how much times does some value repeat in a row but I ran in a problem where my code is leaving the last number without checking it.我试图检查某个值连续重复多少次,但我遇到了一个问题,我的代码在没有检查的情况下留下了最后一个数字。

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)

So let's say I enter: 1 1 1 1 5 5 My code will give an output 5 and not 6所以假设我输入:1 1 1 1 5 5 我的代码将给出输出 5 而不是 6

I hope you understand what I'm saying.我希望你明白我在说什么。 I'm pretty new to python and also this code is not finished, later numbers will be appended so I get the output: [4, 2] because "1" repeats 4 times and "5" 2 times.我对 python 很陌生,而且这段代码还没有完成,后面的数字将被附加,所以我得到输出:[4, 2] 因为“1”重复 4 次,“5”重复 2 次。

Edited - I accidentally wrote 6 and 7 and not 5 and 6.编辑 - 我不小心写了 6 和 7 而不是 5 和 6。

You could use the Counter of the Collections module to measure all the occurrences of different numbers.您可以使用Collections模块的Counter来测量不同数字的所有出现。

from collections import Counter
arr = list(Counter(input().split()).values())
print(arr)

Output with an input of 1 1 1 1 5 5 :输入为1 1 1 1 5 5

1 1 1 1 5 5
[4, 2]

If you want to stick with your method and not use external libraries, you can add an if statement that detects when you reach the last element of your array and process it differently from the others:如果你想坚持你的方法而不使用外部库,你可以添加一个 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)

input输入

[5,5,5,6,6,1]

output输出

[3,2,1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM