Split list item and remove split items if both are not contained in another list in Python -
i have list, called nwk, 2 values in each row. use split() separate values of each row, , compare both of values list of integers, called vals. if both of values in row in nwk not contained in vals, remove row nwk. here have far:
for line in nwk: = [ (int(n) n in line.split()) ] if a[0] not in vals: nwk.remove(line) else: if a[1] not in vals: nwk.remove(line) else: continue however, when print nwk, code has merely removed 1/2 of original lines in nwk, know incorrect. how may fix this? thank in advance help.
filter friend:
filter(lambda line: any(elem in vals elem in line.split()), nwk) nice readings:
- the python language reference »
filter() - the python language reference »
all()/any() - the python language reference »
lambdas
test:
>>> nwk = ['1 2', '3 4', '5 6', '7 8'] >>> vals = ['1', '2', '5', '6', '8'] >>> list(filter(lambda line: any(elem in vals elem in line.split()), nwk)) ['1 2', '5 6', '7 8'] >>>
Comments
Post a Comment