簡體   English   中英

Python:最后一個索引沒有被迭代

[英]Python: Last index is not being iterated

我正在解決一個問題,我得到一個重復數字列表,我必須從初始列表中返回一個包含所有唯一值的新列表。

這是我的解決方案:

new_list = [1,1,1,1,2,2,3,3,3,3,4,5]
updated_lst = []
for i in range(0,len(new_list)-1):
    if new_list[i] != new_list[i+1]:
        updated_lst.append(new_list[i])
print(updated_lst)

Output: [1, 2, 3, 4] 但它缺少 new_list 中的 5。

另外,我是 python 的新手,知道我可以做類似的事情

updated_list = []
for i in new_list:
   if i not in updated_list[]:
       updated_list.append(i)

但我想知道如何使我的初始解決方案發揮作用。

非常感謝

您的問題是range(N, M)內置 function 將從 N 迭代到 M - 1,因此您不應將第二個參數設置為len(new_list)-1而是設置為len(new_list)

請參閱此處的參考資料。

這不會使您的第一個解決方案起作用,但可以解釋為什么您沒有得到最后一個項目。

說這個解決方案不是最優的,通過手動查看索引來實現它的方法是:

new_list = [1,1,1,1,2,2,3,3,3,3,4,5]
updated_lst = []

for i in range(0,len(new_list)):
    found = False

    for j in range(0, len(updated_lst)):
        if new_list[i] == updated_lst[j]:
            found = True
            break

    if not found:
        updated_lst.append(new_list[i])

print(updated_lst)

這對學習都有好處,但我會避免在操場之外使用它,因為它不必要地復雜和不雅。

感謝@ncasale 幫助改進答案。

作為旁注,您的第一個算法不會刪除重復項,而只會刪除重復項。 實現您想要的另一種方法可能是list(set(new_list))

我建議W3schools :對於這個問題,但在你的具體情況下,我會這樣做:

new_list = [1,1,1,1,2,2,3,3,3,3,4,5]
new_list = list(dict.fromkeys(new_list))
print(new_list)

輸出:“[1, 2, 3, 4, 5]”

希望這有幫助

我不確定您的問題是否需要您遍歷列表,但您可以通過將列表轉換為set輕松找到列表中的所有唯一元素。 然后,您可以通過將該set轉換回list list

new_list = [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5]
unique = set(new_list)
print(list(unique))

回報:

[1, 2, 3, 4, 5]

Set是一種無重復元素的無序集合數據類型。 對於所需的 output,我們可以將給定的列表轉換為集合,這將刪除所有重復的元素。 然后我們可以再次將其轉換為列表。 如下:

new_list = [1,1,1,1,2,2,3,3,3,3,4,5]
x=set(new_list)
print(list(x))

這會將 output 打印為:

[1, 2, 3, 4, 5]

這樣我們就可以得到沒有任何重復元素的列表。 希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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