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

我有两个子列表列表:

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


现在,我想扩展listA,使其在listB子列表中的第一项与listA子列表中的项匹配时包含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]
]

10-07 19:20
查看更多