【发布时间】:2021-02-23 12:34:12
【问题描述】:
问题输入:两个列表[1,2,3] 和[4,5,6]
输出:列表以[1,2,3] 排列开头,后跟[4,5,6] 排列
示例输出为[1,2,3,4,5,6]、[3,2,1,4,5,6]、[3,2,1,6,5,4] 等。我想使用生成器循环它们。
我尝试使用以下脚本 (Python3):
from itertools import permutations
def foo():
perm_1 = permutations([1,2,3])
perm_2 = permutations([4,5,6])
for p1 in perm_1:
for p2 in perm_2:
yield list(p1) + list(p2)
f = foo()
for ls in f:
print(ls)
作为输出我得到
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 6, 5]
[1, 2, 3, 5, 4, 6]
[1, 2, 3, 5, 6, 4]
[1, 2, 3, 6, 4, 5]
[1, 2, 3, 6, 5, 4]
如您所见,第一个列表的排列从未使用过,例如输出 [3,2,1,4,5,6] 从未产生。
【问题讨论】:
标签: python python-3.x list generator permutation