【发布时间】: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