Python 如何列出所有可能的排列?
是否有一个函数可以生成列表列表的所有排列,同时保持它们的顺序 例如:Python 如何列出所有可能的排列?,python,list,permutation,Python,List,Permutation,是否有一个函数可以生成列表列表的所有排列,同时保持它们的顺序 例如: func([[1, 2, 3], [10, 20, 30]]) 产生: [[1, 10], [1, 20], [1, 30], [2, 10], [2, 20], [2, 30], [3, 10], [3, 20], [3, 30]] itertools模块中有一个产品函数,它的作用正好是: from itertools import product lst = [[1, 2, 3], [10, 20, 30]] res
func([[1, 2, 3], [10, 20, 30]])
产生:
[[1, 10], [1, 20], [1, 30], [2, 10], [2, 20], [2, 30], [3, 10], [3, 20], [3, 30]]
itertools模块中有一个
产品
函数,它的作用正好是:
from itertools import product
lst = [[1, 2, 3], [10, 20, 30]]
res = [list(i) for i in product(*lst)]
print(res)
因为您希望内部项也是列表,所以我使用list(I)
将product
提供的元组转换为列表
输出:
[[1,10]、[1,20]、[1,30]、[2,10]、[2,20]、[2,30]、[3,10]、[3,20]、[3,30]。
到目前为止,您在搜索此类函数时发现了什么?您已经在Python标准库中看到了itertools
模块了吗?顺便说一句,您所展示的示例称为“笛卡尔积”,而不是“置换”。您正在寻找itertools.product
,而不是permutations