赞
踩
两个元组 (a, b)(c, d)
,则它们的组合有 a,c a,d b,c b,d
通过itertools类生成生成一个列表列表,其中包含两个列表之间的所有潜在组合
import itertools
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8,9]
print(list(itertools.product(list1, list2)))
输出结果:
[(1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9)]
尝试使用列表生成器创建嵌套列表:
>>> [[[x,y] for x in list1] for y in list2]
[[[1, 3], [2, 3]], [[1, 4], [2, 4]]]
或者,如果需要一行列表,只需删除括号:
>>> [[x,y] for x in list1 for y in list2]
[[1, 3], [1, 4], [2, 3], [2, 4]]
repeat第一个列表,permutate第二个列表和zip它们一起
>>> from itertools import permutations, repeat
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))
[[(1, 4), (2, 5), (3, 6)],
[(1, 4), (2, 6), (3, 5)],
[(1, 5), (2, 4), (3, 6)],
[(1, 5), (2, 6), (3, 4)],
[(1, 6), (2, 4), (3, 5)],
[(1, 6), (2, 5), (3, 4)]]
编辑:正如Peter Otten所指出的,内部zip和repeat是多余的。
[list(zip(a, p)) for p in permutations(b)]
《100天精通Python从入门到就业》:本专栏专门针对零基础和需要进阶提升的同学所准备的一套完整教学,从0到100的不断进阶深入,后续还有实战项目,轻松应对面试,专栏订阅地址:https://blog.csdn.net/yuan2019035055/category_11466020.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。