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

问题描述 投票:1回答:1

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

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]]

我尝试为此循环编写以下内容:

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)

但是,这并没有给我所需的输出。谁能帮我这个?

python for-loop list-comprehension permutation
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.