Search code examples
pythonpython-3.xlist-comprehensionnested-loops

Modifying lists within lists via list comprehension


how can I get these loops and if statements into a comprehension?

raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]

for one in raw:
    if one[0] == '-':
        for two in raw:
            if two[1] == one[1] and two[0] == '=': two[0] = '--'

So far:

[two+one for two in raw for one in raw]

But not sure where to put the if statements:

if one[0] == '-' and if two[1] == one[1] and two[0] == '=': two[0] = '--'


Solution

  • A simple list comprehension should be sufficient:

    raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]
    
    res = [['--' if (i != '-') and (['-', j] in raw) else i, j] for i, j in raw]
    

    Result:

    [['-', 'bla'], ['-', 'la'], ['--', 'bla']]