簡體   English   中英

為什么我的代碼沒有檢查列表中的每個值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM