PYTHON remove elements from nested lists -
i have array of arrays this
dataset = [['387230'], ['296163'], ['323434', '311472', '323412', '166282'], ['410119']]
i delete element '311472' not know how. have tried
for set in dataset: item in set: if item=="311472": dataset.remove(item)
but not work
the result should be:
[['387230'], ['296163'], ['323434', '323412', '166282'], ['410119']]
use nested list comprehension, retaining elements instead:
dataset = [[i in nested if != '311472'] nested in dataset]
demo:
>>> [[i in nested if != '311472'] nested in dataset] [['387230'], ['296163'], ['323434', '323412', '166282'], ['410119']]
your mistake remove item
dataset
instead, if removed elements set
you'd end modifying list in place while iterating on it, means further iteration skip elements:
>>> lst = ['323434', '311472', '311472', '323412', '166282'] >>> in lst: ... if == '311472': ... lst.remove(i) ... >>> lst ['323434', '311472', '323412', '166282']
that's because list iterator moves next index regardless of later additions or deletions list; when removing first '311472'
@ index 1 loop moves on index 2 in list past index 1 has moved down spot.
Comments
Post a Comment