Rhys
Rhys

Reputation: 5282

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] = '--'

Upvotes: 0

Views: 61

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12689

You can set item in list comprehension ,

Your code:

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

convert to list comprehension :

[[two.__setitem__(0,'--') if two[1]==one[1] and two[0]=='=' else two for two in raw] if one[0]=='-' else one for one in raw]
print(raw)

output:

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

Upvotes: 0

jpp
jpp

Reputation: 164843

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']]

Upvotes: 2

Related Questions