Wednesday 15 May 2013

Python: Print List Items Not in Separate Index List -



Python: Print List Items Not in Separate Index List -

i have 2 lists: list = ["a","b","c","d"] i_to_skip = [0,2]

i'd print in list except indices in i_to_skip. i've tried following, returns generator object:

print(x x in list if x not in i_to_skip)

the reason comprehension work x value, "a", not index, 0, , of course of study "a" not in [0, 2].

to index along value, need enumerate. can this:

print([x i, x in enumerate(list) if not in i_to_skip])

also, note printing generator look (as did) going print <generator object <genexpr> @ 0x1055fd8b8>; that's why converted code printing out list comprehension, ['b', 'd'] instead.

if instead wanted print, say, 1 line @ time, loop on generator expression:

for x in (x i, x in enumerate(list) if not in i_to_skip): print(x)

but really, it's easier collapse single loop:

for i, x in emumerate(list): if not in i_to_skip: print(x)

or, simpler, format whole thing in single expression, maybe this:

print('\n'.join(x i, x in enumerate(list) if not in i_to_skip))

… or allow print you:

print(*(x i, x in enumerate(list) if not in i_to_skip), sep='\n')

finally, side note, calling list list bad idea; hides type/constructor function, may want utilize later on, , makes code misleading.

python list

No comments:

Post a Comment