【问题标题】:List Comprehension: Nested loop with append statement列表理解:带有 append 语句的嵌套循环
【发布时间】:2019-03-21 01:24:27
【问题描述】:

我有这段python代码

xy_tups = []
for x in ['m', 't', 'b']:
    for y in ['b', 't', 'e']:
        if x != y:
            xy_tups.append ((x, y))

输出这个:[('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b', 'e')]

我需要创建这段代码的列表理解版本,但我无法弄清楚。这些方法我都试过了

 xy_tups = [x for x in ['m', 't', 'b'] and y for y in ['b', 't', 'e'] if x != y] 

 xy_tups = [x for y in ['m', 't', 'b'] and y for x in ['b', 't', 'e'] if x != y]

并且我尝试将xy_tups.append(x,y) 添加到列表理解代码中,但出现错误。我知道x 列表中的每个字母都与y 列表中的每个字母连接一次,但我不知道如何组合列表理解。

【问题讨论】:

标签: python loops nested list-comprehension


【解决方案1】:
xy_tups = [(x,y) for x in ['m , 't', 'b'] for y in ['b', 't', 'e'] if x != y ]
print(xy_tups)

输出: [('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e') , ('b', 't'), ('b', 'e')]

【讨论】:

    【解决方案2】:
    [(a, b) for a in ['m', 't', 'b'] for b in ['b', 't', 'e'] if a != b]
    

    输出

    [('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b','e')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多