Search code examples
pythonlistfor-looplist-comprehensionnested-loops

Nested List Comprehensions Example


Problem

I have next list:

a = (('_a_1', '_a_2'), [0.3, 0.6]) 
b = (('_a_3', '_a_4'), [0.15, 0.56]) 
c = (('_a_5', '_a_6'), [0.22, 0.6])

l = [a, b, c]

What I wan't: choose first tuples of list and remove _a_ labels. Result:

[['1','2'],['3','4'],['5','6']]

What I tried

I know I can do it using list comprehension. But I can't comprehend it :D What I'm trying:

[ el.replace('_a_','') for m in l for el in m[0]]

result:

['1', '2', '3', '4', '5', '6']

I think it is closed to right solution. Just add something like:

[ [el.replace('_a_','') for m in l] for el in m[0]]

But it doesn't work...


Solution

  • You were close:

    a = (('_a_1', '_a_2'), [0.3, 0.6]) 
    b = (('_a_3', '_a_4'), [0.15, 0.56]) 
    c = (('_a_5', '_a_6'), [0.22, 0.6])
    
    l = [a, b, c]
    
    [ [el.replace('_a_','') for el in tup[0]] for tup in l]
    # [['1', '2'], ['3', '4'], ['5', '6']]