Friday, 15 July 2011

Remove from list with Python list comprehension -



Remove from list with Python list comprehension -

why isn't number 4 removed next list?

>>> list=[1,2,3,4] >>> [list.remove(item) item in list if item > 2] [none] >>> list [1, 2, 4]

also, i'm trying remove items lista if item found in listb. how can list comprehension?

also, how do:

list2=["prefix1","prefix2"] [item item in list if not "item starts prefix in list2"] # pseudocode

first of all, using list comprehension side effects bad practice. should use

lst = [x x in lst if x <= 2]

additionally, don't utilize list variable name, because taken builtin list. 3rd of all, approach not working because iterating on list while mutating it.

here's demo of what's happening approach:

# python interpreter >>> lst = [1,2,3,4] >>> item in lst: ... print(item) ... if item > 2: ... lst.remove(item) ... print(lst) ... 1 [1, 2, 3, 4] 2 [1, 2, 3, 4] 3 [1, 2, 4]

as can see, item never 4.

as sec question:

also, i'm trying remove items lista if item found in listb. how can list comprehension?

bset = set(listb) lista = [x x in lista if x not in bset]

as 3rd question:

>>> list1=['prefix1hello', 'foo', 'prefix2hello', 'hello'] >>> prefixes=['prefix1', 'prefix2'] >>> [x x in list1 if not any(x.startswith(prefix) prefix in prefixes)] ['foo', 'hello']

please stop adding new questions now, can open new question different problem, thanks.

python list list-comprehension

No comments:

Post a Comment