PYTHON从嵌套列表中删除元素 [英] PYTHON remove elements from nested lists
问题描述
我有一个这样的数组数组
I have an array of arrays like this
dataSet = [['387230'], ['296163'], ['323434', '311472', '323412', '166282'], ['410119']]
我想删除元素"311472",但不知道如何.我尝试过
I would like to delete element '311472' but do not know how. I have tried
for set in dataSet:
for item in set:
if item=="311472":
dataSet.remove(item)
但这不起作用
结果应为:
[['387230'], ['296163'], ['323434', '323412', '166282'], ['410119']]
推荐答案
使用嵌套列表理解,改为保留元素:
Use a nested list comprehension, retaining elements instead:
dataSet = [[i for i in nested if i != '311472'] for nested in dataSet]
演示:
>>> [[i for i in nested if i != '311472'] for nested in dataSet]
[['387230'], ['296163'], ['323434', '323412', '166282'], ['410119']]
您的错误是改为从dataSet
中删除item
,但是即使从set
中删除了元素,您最终还是要在迭代列表的同时修改列表,这意味着进一步的迭代将 skip 元素:
Your mistake was to remove item
from dataSet
instead, but even if you removed the elements from set
you'd end up with modifying the list in place while iterating over it, which means that further iteration will skip elements:
>>> lst = ['323434', '311472', '311472', '323412', '166282']
>>> for i in lst:
... if i == '311472':
... lst.remove(i)
...
>>> lst
['323434', '311472', '323412', '166282']
这是因为列表迭代器移至下一个索引,而不管以后对列表的添加或删除.当删除索引1处的第一个'311472'
时,循环将移至列表中的索引2,其中所有 past 索引1都向下移动了一个点.
That's because the list iterator moves to the next index regardless of later additions or deletions from the list; when removing the first '311472'
at index 1 the loop moves on to index 2 in a list where everything past index 1 has moved down a spot.
这篇关于PYTHON从嵌套列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!