0

The code below needs three lines. Is it possible to simplified to one line?

code = [x for x in code if not 'W' in x]
code = [x for x in code if not '06501' in x]
code = [x for x in code if not '06502' in x]

I was trying this but did not work

code = [x for x in code if not 'W' or if not '06501' or if not '06502' in x]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
bkcollection
  • 913
  • 1
  • 12
  • 35
  • Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – jonrsharpe Apr 22 '17 at 07:59
  • can you update sample of code variable, what its look like? – Hackaholic Apr 22 '17 at 08:15

3 Answers3

2

Better you can do like this:

remove_item = ['w', '06501', '06502']
code = [x for x in code if x not in remove_item]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • 1
    This is not the same OP requirement. You are checking if `x` matches any item in `remove_item`. OP's requirement if any any item in `remove_item` occurs in `x` – shanmuga Apr 22 '17 at 08:14
  • That doesn't appear to work on the test case in my answer - returns all items. – Darkstarone Apr 22 '17 at 08:14
  • I did in my answer. I'm not OP, so my test case could be wrong, but it worked with the original code OP provided. (`code = [['W'],['06501'],['06502'],["hi"]]`) – Darkstarone Apr 22 '17 at 08:17
1

This is one way to do it

[ x for x in code if not any( i in x for i in ['W', '06501', '06502'])]

An alternate version

[ x for x in code if not any(map(lambda i: i in x, remove_items)) ]

Modifying the same to use filter

filter(lambda x: not any(map(lambda i: i in x, remove_items)), code)

Note: The choice of which semantic to use is mostly personal preference. However the last version may be better is code is large since it returns a generator object for lazy evaluation (in python3)

shanmuga
  • 4,329
  • 2
  • 21
  • 35
0

This should work.

code = [x for x in code if not ('W' in x or '06501' in x or '06502' in x)]

This works for the following input:

code = [['W'],['06501'],['06502'],["hi"]]
code = [x for x in code if not ('W' in x or '06501' in x or '06502' in x)]
# >> code: [['hi']]

You could also use an array like so:

disallowed_values = ['W', '06501', '06502']

code = [ x for x in code if not any(y in x for y in disallowed_values)]
Darkstarone
  • 4,590
  • 8
  • 37
  • 74