【问题标题】:Permutation of nested lists in Python [duplicate]Python中嵌套列表的排列[重复]
【发布时间】:2026-01-05 18:10:01
【问题描述】:

想象一个列表列表,如下所示:

x=[['foo','bar'],['baz'],['xyz']]

除了更长。我需要一个脚本来为包含少量单词的任意长度列表生成排列,也是任意长度。

所以,在这种情况下:

[['foo','bar'],['baz'],['xyz']]
[['foo','bar'],['xyz'],['baz']]
[['xyz'],['baz'],['foo','bar']]
[['baz'],['xyz'],['foo','bar']]
[['xyz'],['foo','bar'],['baz']]
[['baz'],['foo','bar'],['xyz']]

我无法使用 itertools 来管理它。有什么建议吗?

【问题讨论】:

  • 在itertools中有一个直接的功能。到目前为止你做了什么?你被困在哪里了?请在问题中包含您的尝试,以便我们帮助您更正。
  • 欢迎来到 SO! itertools.permutations(x)! (尽管您的订购要求相当不寻常/不一致......不确定这是否重要)

标签: python text permutation itertools combinatorics


【解决方案1】:

从 itertools 尝试permutations()

from itertools import permutations
x=[['foo','bar'],['baz'],['xyz']]
for y in permutations(x):
  print(y)

【讨论】: