[英]How to make couple for elements from two list (different size) in Python?
我需要为两个列表中的元素制作一对(两个列表的大小不同)
前任:
x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
结果:
new_list = ([3, -5], [3, 1], [3, 4], [3, 13], [3, 9], [3, 7], [3, 5], [3, -1],[3, 10], [2, -5], [2, 1] ......<sorry, there're too many>.... [-8, 5], [-8, -1], [-8, 10])
谢谢支持!
分两步,1) 展平列表列表,2) itertools.product
扁平化列表列表: 如何从列表列表中制作扁平化列表
flat_list = [item for sublist in t for item in sublist]
使用 itertools 创建两个列表的乘积。
itertools.product(x, y)
来自 OP 的示例:
x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_flat = [item for sublist in x for item in sublist]
y_flat = [item for sublist in y for item in sublist]
list(itertools.product(x_flat, y_flat))
结果:
[(3, -5), (3, 1), (3, 4), (3, 13), (3, 9), (3, 7), (3, 5), (3, -1), (3, 10), (2, -5), (2, 1), (2, 4), (2, 13), (2, 9), (2, 7), (2, 5), (2, -1), (2, 10), (4, -5), (4, 1), (4, 4), (4, 13), (4, 9), (4, 7), (4, 5), (4, -1), (4, 10), (6, -5), (6, 1), (6, 4), (6, 13), (6, 9), (6, 7), (6, 5), (6, -1), (6, 10), (-8, -5), (-8, 1), (-8, 4), (-8, 13), (-8, 9), (-8, 7), (-8, 5), (-8, -1), (-8, 10)]
示例中的x
, y
和new_list
实际上是元组而不是列表,因为您使用()
而不是[]
。
根据您的预期结果,我假设您在这里并不需要列表列表,您只需采用平面列表:
x = [3,2,4,6,-8]
y = [-5,1,4,13,9,7,5,-1,10]
并找到x
和y
之间的每个组合。 可以使用itertools.product
来完成
from itertools import product, chain
new_list = list(product(chain(*x), chain(*y)))
[(3, -5), (3, 1), (3, 4), (3, 13), (3, 9), (3, 7), (3, 5), (3, -1), (3, 10), (2, -5), (2, 1), (2, 4), (2, 13), (2, 9), (2, 7), (2, 5), (2, -1), (2, 10), (4, -5), (4, 1), (4, 4), (4, 13), (4, 9), (4, 7), (4, 5), (4, -1), (4, 10), (6, -5), (6, 1), (6, 4), (6, 13), (6, 9), (6, 7), (6, 5), (6, -1), (6, 10), (-8, -5), (-8, 1), (-8, 4), (-8, 13), (-8, 9), (-8, 7), (-8, 5), (-8, -1), (-8, 10)]
首先,您有两个包含列表的元组,而不是数字列表,并且预期结果是包含两个长度列表的元组。 因此,您必须首先将这些列表元组转换为简单元组,遵循此解决方案(稍作更改): https://stackoverflow.com/a/952952/11882999
x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_tuple = tuple(item for sublist in x for item in sublist)
y_tuple = tuple(item for sublist in y for item in sublist)
然后按照这个解决方案(稍加改动),您可以轻松计算两个元组的组合: https://stackoverflow.com/a/39064769/11882999
result = tuple([x, y] for x in x_tuple for y in y_tuple)
>> ([3, -5], [3, 1], [3, 4], ..., [-8, 5], [-8, -1], [-8, 10])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.