如何才能将这些loops
和if statements
纳入理解中?
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] = '--'
到目前为止:
[two+one for two in raw for one in raw]
但不确定if语句的位置:
if one[0] == '-'
和if two[1] == one[1] and two[0] == '=': two[0] = '--'
答案 0 :(得分:2)
简单的列表理解应该足够了:
raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]
res = [['--' if (i != '-') and (['-', j] in raw) else i, j] for i, j in raw]
结果:
[['-', 'bla'], ['-', 'la'], ['--', 'bla']]
答案 1 :(得分:0)
您可以在列表理解中设置项目,
您的代码:
for one in raw:
if one[0] == '-':
for two in raw:
if two[1] == one[1] and two[0] == '=': two[0] = '--'
转换为列表理解:
[[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)
输出:
[['-', 'bla'], ['-', 'la'], ['--', 'bla']]