2014-06-25 58 views
0

我無法理解爲什麼我的代碼無法工作。 我試圖從在長度只有一個字符一個列表中刪除的話:從列表中刪除單個字符

line = ['word','a','b','c','d','e','f','g'] 
for words in line: 
    if len(words) == 1: 
     line.remove(words) 

此代碼返回的(這看起來去除「所有其他」單個字符):

燦任何人都可以解釋爲什麼這不能正常工作以及如何解決?

+3

很常見的錯誤。在迭代時不要修改列表。以下答案提供了實現預期結果的正確方法 – sshashank124

回答

5

這樣做:

line = ['word','a','b','c','d','e','f','g'] 
line = [i for i in line if len(i) > 1] 

與您的代碼的問題是,您是從列表中刪除,而迭代這是不是安全的。它會改變列表的長度:

line = ['word','a','b','c','d','e','f','g'] 
iterated = 0 
removed = 0 
for words in line: 
    iterated += 1 
    if len(words) == 1: 
     line.remove(words) 
     removed += 1 

print line # ['word', 'b', 'd', 'f'] 
print iterated # 5 
print removed # 4