在两个列表列表之间执行操作并跟踪初始列表

时间:2017-04-23 12:43:15

标签: python list

我有些想法,我觉得写作很困惑。请原谅我,我现在就跳进去。

基本上,我有两个列表列表,每个列表中包含不同数量的元素。

L1 = [[1.1,1.2],[1.3,1.4]]
L2 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]

在我的代码行中,我有一个定义函数来查找'作为参数'的两个列表之间的最短距离。例如,在 L1 中,提取第一个列表,即[1.1,1.2],在 L2 中,第一个列表,即[2.1,2.2]被提取出来。然后这个列表都会通过返回值的函数。然后将[1.1,1.2]等过程与[2.3,2.4]进行比较,依此类推,直到没有更多要素进行比较。然后将从函数获得的值作为输出附加到列表中,其中我得到如下内容:

outputL = [values,values,values..... and so on as there are many combinations]

我现在面临的问题是无法跟踪L1中哪个列表与L2中的列表配对,同时通过该功能。

示例:

获得的L1中的第一个列表是[1.1,1.2],L2是[2.1,2.2] ==>通过功能==>获得价值==>附在列表上。

现在而不是列表中的所有值,我想至少在列表中的值旁边显示L1或L2的列表元素,这样我就可以跟踪哪些值属于哪个列表。

expected output would be something like : [values,1.1,1.2, values,1.3,1.4...so on]

我有一个代码:

outputL = []
for i in L1:
   for j in L2:
       results = shortest_distance(i,j) #shortest_distance is the defined function that takes two lists as it's parameter
       outputL.append(results)
print(outputL)

1 个答案:

答案 0 :(得分:1)

您要找的是itertools.product

此功能将生成您提供的列表之间所有可能组合的列表。

在您自己的2个列表示例中,结果如下:

list( product( L1, L2 ) )
Out[56]: 
[([1.1, 1.2], [2.1, 2.2]),
 ([1.1, 1.2], [2.3, 2.4]),
 ([1.1, 1.2], [2.5, 2.6]),
 ([1.3, 1.4], [2.1, 2.2]),
 ([1.3, 1.4], [2.3, 2.4]),
 ([1.3, 1.4], [2.5, 2.6])]

然后,您可以迭代组合并运行距离函数。在下面的示例中,我使用了欧几里德距离,因为您没有提供自己的距离函数,但您当然可以将euclidean替换为您自己的shortest_distance

L1 = [[1.1,1.2],[1.3,1.4]]
L2 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]

from scipy.spatial.distance import euclidean
from itertools import product

outputL = [ euclidean( a, b ) for pair in product( L1, L2 ) for a, b in pair ]