通过列表理解修改列表中的列表

时间:2018-03-19 01:36:32

标签: python python-3.x list-comprehension nested-loops

如何才能将这些loopsif 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] = '--'

2 个答案:

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