Access list items that are not equal to a specific value

I am browsing a list like this:

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

and I want to see what elements have 'a'. Therefore, first I need to find the lists in which it occurs 'a'. Then access another list item. I do it withabs(pair.index('a')-1)

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

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

UPDATE:

  • It may be useful to note that this is 'a'not necessarily the first element.

  • ['a','a']doesn't happen in my case , but it can usually be useful to choose a solution that also handles this situation

+4
source share
3 answers

, a? , :

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

, , a :

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

set, a , .

+5

, :

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

, python 3 . list(), .

0

, , . .

def paired_with(seq, ch):
    chset = set(ch) 
    return [(set(pair) - chset).pop() for pair in seq if ch in pair]

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

print(paired_with(my_list, 'a'))

['b', 'x']

, .

def paired_with(seq, ch):
    chset = set(ch) 
    return [(pair - chset).pop() for pair in seq if ch in pair]

my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r']]
my_sets = [set(u) for u in my_list]
print(my_sets)
print(paired_with(my_sets, 'a'))

[{'b', 'a'}, {'c', 'b'}, {'x', 'a'}, {'r', 'f'}]
['b', 'x']

, , ['a', 'a'], :

def paired_with(seq, ch):
    chset = set(ch) 
    return [(pair - chset or chset).pop() for pair in seq if ch in pair]

my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r'], ['a', 'a']]
my_sets = [set(u) for u in my_list]
print(paired_with(my_sets, 'a'))

['b', 'x', 'a']
0

Source: https://habr.com/ru/post/1683216/


All Articles