Skip to main content
 首页 » 编程设计

Python 从子列表中提取项目,如果它们与另一个列表的子列表中的项目匹配

2024年09月07日8zhwl

对于令人困惑的标题,我深表歉意。我想知道比较两个子列表列表的最佳方法是什么,如果子列表中的项目与另一个列表的子列表中的项目匹配,则前一个列表会扩展为后者的项目。我知道这听起来很困惑,所以这里是详细信息:

我有两个子列表列表:

listA = [['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']] 
listB = [['z', 7, 8, 9], ['x', 1, 2, 3], ['y', 4, 5, 6]] 

现在我想扩展 listA,如果 listA 的子列表中的第一项匹配,它包含 listB 中的值listB 的子列表。所以基本上,最终结果应该如下:

listA = [['x', 'apple', 'orange', 1, 2, 3], ['y', 'cat', 'dog', 4, 5, 6], ['z', 'house', 'home', 7, 8, 9]] 

这是我尝试过的:

for (sublistA, sublistB) in zip(listA, listB): 
    if sublistA[0] == sublistB[0]: 
        sublistA.extend(sublistB[1], sublistB[2], sublistB[3]) 

但是,代码似乎在 if 语句处失败了。当我打印 listA 时,我得到的只是它的原始项目:

>>> print(listA) 
[['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']] 

为什么 if 语句不起作用?有什么方法可以进行这种匹配然后提取项目?

编辑: 根据 idjaw 的建议,我创建了第三个列表并尝试再次执行上述操作。但是,我似乎得到了一个空列表,因为 if 语句似乎不再起作用。这是代码:

listC = [] 
for (sublistA, sublistB) in zip(listA, listB): 
    if sublistA[0] == sublistB[0]: 
        listC.append(sublistA[0], sublistA[1], sublistA[2],  
                     sublistB[1], sublistB[2], sublistB[3]) 
print(listC) 

输出:[]

请您参考如下方法:

这是一种通过构建字典来实现此目的的方法,以便更轻松地查找要添加到的列表:

代码:

lookup = {x[0]: x for x in listA} 
for sublist in listB: 
    lookup.get(sublist[0], []).extend(sublist[1:]) 

测试代码:

listA = [['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']] 
listB = [['z', 7, 8, 9], ['x', 1, 2, 3], ['y', 4, 5, 6]] 
 
lookup = {x[0]: x for x in listA} 
for sublist in listB: 
    lookup.get(sublist[0], []).extend(sublist[1:]) 
 
print(listA) 

结果:

[ 
    ['x', 'apple', 'orange', 1, 2, 3],  
    ['y', 'cat', 'dog', 4, 5, 6],  
    ['z', 'house', 'home', 7, 8, 9] 
]