簡體   English   中英

通過刪除列表元素更改循環范圍

[英]Change in for-loop range by deleting a list element

我是python和程序設計的新手,目前正在學習基礎知識。 在下面的腳本中,我嘗試檢查每個列表元素中的字母數,並刪除五個或更多字母的字母。 我正在使用for循環來實現此目的,但是由於列表元素數量的變化與最初考慮的for循環范圍不對應,因此出現了問題。 我試圖讓范圍自行變化,但仍然出現錯誤。

# -*- coding: utf-8 -*-

magicians =['alice','david','carolina']

def counter(word):
    x= sum (c != ' ' for c in word)
    return x

print magicians
for i in range (0,3):
        magicians[i]=magicians[i].title()
print magicians
q=
Y=range (0,q)

for i in Y:
    x= counter(magicians[i])
    print x    
    if x<=5:
        print 'this component will be deleted:', magicians[i]
        del magicians[i]
        q=q-1
        Y=range (0,q)
print magicians

謝謝

您的代碼的主要問題是循環內的Y = ...Yfor i in YY in 沒有影響。

for i in Y:
    ...
        Y=range (0,q)

可以更改代碼以使用while循環,並手動管理當前索引和最大索引,但這很容易出錯:

i = 0
while i < q:
    x= counter(magicians[i])
    if x<=5:
        print 'this component will be deleted:', magicians[i]
        del magicians[i]
        q=q-1
    else:
        i += 1

與其在迭代相同列表的同時從列表中刪除元素,不如在第二個列表中填充僅包含您要保留的元素的更好的做法,例如使用列表理解:

good_magicians = [m for m in magicians if counter(m) > 5]

這篇文章對您的問題有一個詳盡的答案: 迭代時從列表中刪除項目

最簡單的方法是創建一個僅包含您實際需要的元素的新列表。

暫無
暫無

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

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