python - 从 n 个整数列表(可能长度不等)中进行所有可能的 n 长度排列

标签 python algorithm combinations permutation python-itertools

示例:

list1 = [0,1,2]
list2 = [0,1]
list3 = [0,1,2,3]

那么排列将是:

0,0,0
0,0,1
0,0,2
0,0,3
0,1,0
0,1,1
0,1,2
0,1,3
1,0,0
1,0,1
1,0,2
1,0,3
1,1,0
1,1,1
1,1,2
1,1,3

...等等,有 3 x 2 x 4 = 24 种排列。

列表的数量不一定是 3(它们可以是任何数字 n),并且顺序很重要,因此 0,0,1 与 0,1,0 不同。

我知道我可能必须以某种方式使用 itertools,但不知道如何解决这个问题。我不能只创建三个嵌套循环,因为列表的数量各不相同。

这是 this question 的变体,但列表的数量各不相同并且顺序很重要。

我感谢任何帮助或提示。谢谢。

最佳答案

list1 = [0,1,2]
list2 = [0,1]
list3 = [0,1,2,3]
listOfLists = [list1,list2,list3]
for list in itertools.product(*listOfLists):
    print(list)  

关于python - 从 n 个整数列表(可能长度不等)中进行所有可能的 n 长度排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203566/

相关文章:

python - 在 Heroku 中设置 Python Conda 环境

algorithm - 生成给定长度的 0's and 1' 的所有组合,最小和最大为 1

r - 如何将我现有的 R 代码从随机样本的输出更改为所有可能结果的列表?

java - Google Foobar 挑战 3 - 找到访问代码

Python/格式 - 列表和宽度

python - 使用 GObjects 发送通知

python - pydantic:创建模型实例时如何忽略无效值

algorithm - 最大多样性 : translate an heuristic algorithm in C (or pseudocode)

python - 查找数组中第 n1 个最小数字到第 n2 个最小数字的快速算法

java - 使用平行于 X 轴的线的孵化算法