取下列表中的元素,我有以下列表:根據具體內容
['10 .10.10.10' ,'20 .20.20.20' ,'30 .30.30.30' ,'10 .20.30.40 | locationInherited =真」, '40.40.40.40','8.8.8.8 | locationInherited = true']
我需要刪除包含'| locationInherited = true'的所有元素,所以'10.20.30.40 | locationInherited = true'&'8.8。 8.8 | locationInherited = true'需要被移除,因此所有留在列表中的是['10.10.10.10','20.20.20.20','30.30.30','40.40.40.40']
我有試過
for elem in list:
if '|locationInherited=true' in elem:
list.remove(elem)
而且
while list.count('|locationInherited=true') > 0:
list.remove('|locationInherited=true')
既不產生一個錯誤,但既不取出所有必要的元件。
的[從列表中刪除項目,而迭代]可能的複製(https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) –
列表用'if'| locationInherited = true'not in elem'來理解元素被複制到新列表中的情況可能是要走的路 –
您不應該在迭代列表時從列表中移除它。你可以建立一個新的列表,但是這是列表解析的部分:'l = [e如果'| locationInherited = true'不在e中] –