Skip to main content
 首页 » 编程设计

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

2025年02月15日7mq0036

我有一些想法,我觉得写起来很困惑。请原谅我,我现在就开始。

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

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

在我的代码行中,我有一个定义的函数来查找“作为参数的两个列表之间的最短距离”。例如,在 L1 中,first list 是 [1.1,1.2] 被提取,同样在 L2 中,first list 即 [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) 

请您参考如下方法:

您要找的是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 ]