Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access list elements that are not equal to a specific value

Tags:

python

I am searching through a list like this:

my_list = [['a','b'],['b','c'],['a','x'],['f','r']]

and I want to see which elements come with 'a'. So first I have to find lists in which 'a' occurs. Then get access to the other element of the list. I do this by abs(pair.index('a')-1)

for pair in my_list:
    if 'a' in pair:
       print( pair[abs(pair.index('a')-1)] )

Is there any better pythonic way to do that?
Something like: pair.index(not 'a') maybe?

UPDATE:

  • Maybe it is good to point out that 'a' is not necessarily the first element.

  • in my case, ['a','a'] doesn't happen, but generally maybe it's good to choose a solution which handles this situation too

like image 217
Alireza Avatar asked Aug 08 '17 06:08

Alireza


2 Answers

Are you looking for elements that accompany a? If so, a simple list comprehension will do:

In [110]: [x for x in my_list if 'a' in x]
Out[110]: [['a', 'b'], ['a', 'x']]

If you just want the elements and not the pairs, how about getting rid of a before printing:

In [112]: [(set(x) - {'a'}).pop() for x in my_list if 'a' in x]
Out[112]: ['b', 'x']

I use a set because a could either be the first or second element in the pair.

like image 105
cs95 Avatar answered Nov 12 '22 12:11

cs95


If I understand your question correctly, the following should work:

my_list = filter(
   lambda e: 'a' not in e,
   my_list
)

Note that in python 3, this returns a filter object instance. You may want to wrap the code in a list() command to get a list instance instead.

like image 41
Henning Avatar answered Nov 12 '22 13:11

Henning