2016-09-26 55 views
-4

正如您所看到的,我试图删除列表中单词的长度为1或2,但无法找到“P”和“ye”并删除!python:无法删除列表中的单词

enter image description here

enter image description here

+0

你正在修改列表,因为你正在迭代它。 –

+1

[在Python中迭代时从列表中删除项目]可能的重复(http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – SiHa

回答

0

看看这个代码:

li = ['of','in','a','bb','abbb'] 
lii = [] 
for i in li: 
    j = len(i) 
    if j == 1 or j == 2: 
    lii.append(i) 

for i in lii: 
    li.remove(i) 

print li 

输出:

['abbb'] 
0

,而你遍历它不能修改列表。 但你可以这样做:

L = ['of', 'P', 'representig', 'the', 'subs', 'et', 'ye', 'ti'] 

result = [i for i in L if len(i) != 1 and len(i) != 2]