【问题标题】:Transform a list comprehension to simple for loop将列表理解转换为简单的 for 循环
【发布时间】:2019-03-02 22:04:47
【问题描述】:

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

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)

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

【问题讨论】:

  • 为什么会被否决?
  • 不知道。我不明白为什么人们甚至不建议更改或编辑就这样做。

标签: python for-loop list-comprehension permutation


【解决方案1】:
[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

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多