1

I have a list, called nwk, with two values in each row. I would like to use split() to separate the values of each row, and then compare both of those values to another list of integers, called vals. If both of the values in a row in nwk are not contained in vals, I would like to remove that row from nwk. Here is what I have so far:

for line in nwk:
    a = [ (int(n) for 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 I print nwk, the code has merely removed 1/2 of my original lines in nwk, which I know to be incorrect. How may I fix this? Thank you in advance for your help.

Daniel
  • 159
  • 1
  • 3
  • 9

4 Answers4

0

if you want to remove the line if both vals in a are in vals then Ou could compare list a to list vals as described in this answer And remove the line if True.

like this:

set(['a', 'b']).issubset(['a', 'b', 'c'])

To use a set makes sense since it removes all double entries in a list.

Community
  • 1
  • 1
klaas
  • 1,661
  • 16
  • 24
0

Here's a sample code:

new_list = list()
for line in nwk:
    row_a, row_b = line.split()
    if (row_a not in vals) and (row_b not in vals):
        new_list.append(line)
CristiFati
  • 38,250
  • 9
  • 50
  • 87
  • This was also a very helpful response. I was able to use "in" rather than "not in" and get my desired results. Thank you for your input! – Daniel Apr 29 '15 at 01:04
0

You can use a list comprehension:

[row for row in nwk if row[0] in vals and row[1] in vals]

This will produce a subset of nwk where each value in columns 1 and 2 are both in val.

nwk = [[1, 2], [3, 4], [5, 6], [7, 8]]
vals = [1, 2, 5, 6, 8]

>>> [row for row in nwk if row[0] in vals and row[1] in vals]
[[1, 2], [5, 6]]
Alexander
  • 105,104
  • 32
  • 201
  • 196
0

filter is your friend:

filter(lambda line: any(elem in vals for 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 for elem in line.split()), nwk))
['1 2', '5 6', '7 8']
>>>
fferri
  • 18,285
  • 5
  • 46
  • 95