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] = '--'
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']]
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']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.