有没有办法将此列表理解更改为普通循环

时间:2020-08-15 16:58:19

标签: python-3.x

无论如何,是否可以将此列表理解方式更改为正常的循环表示方式。

result=[[]]
result = [x+[y] for x in result for y in sublist]

编辑:

这是完整的代码,我正在尝试使用循环来理解。

result = [[]]
mainlist = [(1,2,3), (1,2,3)]
print(mainlist)
  for sublist in mainlist:
    result = [x+[y] for x in result for y in sublist]
  print(result)

输出(结果):

[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

2 个答案:

答案 0 :(得分:0)

输出将为out

x = []  # OP was assigning this constant expression to x.
out = []
for y in sublist:
    out.append(x + [y])

答案 1 :(得分:0)

这很棘手,因为它本质上不是列表理解本身,而是结合列表理解的for循环。

result = [[]]
mainlist = [(1,2,3), (1,2,3)]

for sublist in mainlist:
    out = []
    for x in result:
        for y in sublist:
            out.append(x+[y])
    result = out
print(result)