将列表理解转换为简单的for循环

时间:2019-03-02 22:04:48

标签: python for-loop list-comprehension permutation

鉴于输入包含所有唯一数字,我有一个列表推导返回所有可能排列的列表。

nums = [1,2,3]
ans = [[]]
for x in nums:
    ans = [items + [n] for items in ans for n in nums if (n not in items)]
print(ans)

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

我试图为所有以下内容编写for循环:

nums = [1, 2, 3]
ans = [[]]

for x in nums:
    for items in ans:
        for n in nums:
            if n not in items:
                items.append(n)
print(ans)

但是,这不能提供所需的输出。有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

[items + [n] for items in ans for n in nums if (n not in items)]

让我们分解一下,从右到左。

for items in ans:
    for n in nums:
        if n not in items:

然后,您只需创建一个列表并将这些items + [n]添加到其中

result = []
for items in ans:
    for n in nums:
        if n not in items:
            result.append(items + [n])

现在,这整个事情是从另一个循环for x in nums内部执行的。所以你有:

nums = [1,2,3]
ans = [[]]

for x in nums:
    result = []
    for items in ans:
        for n in nums:
            if n not in items:
                result.append(items + [n])
    ans = result