我需要為兩個串列中的元素創建一對(兩個串列的大小不同)
例如:
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])
謝謝支持!
uj5u.com熱心網友回復:
分兩步,1) 展平你的串列,2) itertools.product
扁平化串列串列:如何從串列串列中 制作扁平化串列
flat_list = itertools.chain(*iterable_of_lists)
使用 itertools 創建兩個串列的乘積。
itertools.product(x, y)
來自 OP 的示例:
import itertools
x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_flat = itertools.chain(*x)
y_flat = itertools.chain(*y)
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)]
uj5u.com熱心網友回復:
您的x,y和new_list在示例中實際上是元組而不是串列,因為您使用的是()代替[]。
根據您的預期結果,我假設您在這里并不真正需要串列串列,您只需使用平面串列:
x = [3,2,4,6,-8]
y = [-5,1,4,13,9,7,5,-1,10]
并找到x和之間的每個組合y。可以使用itertools.product
uj5u.com熱心網友回復:
使用和:itertools chainproduct
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)]
uj5u.com熱心網友回復:
首先,您有兩個包含串列的元組,而不是數字串列,預期結果是一個包含兩個長度串列的元組。因此,您必須首先按照此解決方案(稍作更改)將這些串列元組轉換為簡單元組: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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388309.html
上一篇:如何確定串列中元素的負索引?
