Python| N个列表的所有可能排列
计算排列始终是许多实际应用中的一项必要任务,也是数学中广泛使用的概念,以解决许多实际问题。让我们讨论一些可以执行获取 N 个列表的所有排列的任务的方法。
方法#1:使用列表推导
列表推导可用于将天真的方法任务转换为单行,因此更紧凑。此方法检查每个元素的可用元素并相应地进行配对。
# Python3 code to demonstrate
# to compute all possible permutations
# using list comprehension
# initializing lists
list1 = [1, 3, 4]
list2 = [6, 7, 9]
list3 = [8, 10, 5]
# printing lists
print ("The original lists are : " + str(list1) +
" " + str(list2) +
" " + str(list3))
# using list comprehension
# to compute all possible permutations
res = [[i, j, k] for i in list1
for j in list2
for k in list3]
# printing result
print ("All possible permutations are : " + str(res))
输出 :
The original lists are : [1, 3, 4] [6, 7, 9] [8, 10, 5]
All possible permutations are : [[1, 6, 8], [1, 6, 10], [1, 6, 5], [1, 7, 8], [1, 7, 10], [1, 7, 5], [1, 9, 8], [1, 9, 10], [1, 9, 5], [3, 6, 8], [3, 6, 10], [3, 6, 5], [3, 7, 8], [3, 7, 10], [3, 7, 5], [3, 9, 8], [3, 9, 10], [3, 9, 5], [4, 6, 8], [4, 6, 10], [4, 6, 5], [4, 7, 8], [4, 7, 10], [4, 7, 5], [4, 9, 8], [4, 9, 10], [4, 9, 5]]
方法#2:使用itertools.product()
使用产品函数,可以以更 Pythonic 和简洁的方式轻松执行此任务。这是执行此计算笛卡尔积任务的最推荐方法。
# Python3 code to demonstrate
# to compute all possible permutations
# using itertools.product()
import itertools
# initializing list of list
all_list = [[1, 3, 4], [6, 7, 9], [8, 10, 5] ]
# printing lists
print ("The original lists are : " + str(all_list))
# using itertools.product()
# to compute all possible permutations
res = list(itertools.product(*all_list))
# printing result
print ("All possible permutations are : " + str(res))
输出 :
The original lists are : [[1, 3, 4], [6, 7, 9], [8, 10, 5]]
All possible permutations are : [(1, 6, 8), (1, 6, 10), (1, 6, 5), (1, 7, 8), (1, 7, 10), (1, 7, 5), (1, 9, 8), (1, 9, 10), (1, 9, 5), (3, 6, 8), (3, 6, 10), (3, 6, 5), (3, 7, 8), (3, 7, 10), (3, 7, 5), (3, 9, 8), (3, 9, 10), (3, 9, 5), (4, 6, 8), (4, 6, 10), (4, 6, 5), (4, 7, 8), (4, 7, 10), (4, 7, 5), (4, 9, 8), (4, 9, 10), (4, 9, 5)]