繁体   English   中英

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

[英]Python Extracting items from a sublist if they match an item in another list's sublist

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

我有两个子列表列表:

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)

输出: []

这是通过构建 dict 来允许更轻松地查找要添加到的列表的一种方法:

代码:

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]
]

也许你的代码可能是这样的

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



for la in listA:
    for lb in listB:
        if la[0] == lb[0]:
            for i in lb[1:]:
                la.append(i)

print(listA)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM