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

标签 python list string-matching

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

我有两个子列表列表:

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

关于Python 如果子列表中的项目与另一个列表的子列表中的项目匹配,则从子列表中提取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48615790/

相关文章:

python - 提取元组并用 int 迭代覆盖

python - 请求 URL 后推送数据

python - 如何对列表进行排序首先写入相同的元素,然后按升序排列

要听写的元组的 Python 列表

java - 确定字符串是否有内部单词边界

给定相似度得分的最佳匹配项目对的算法

algorithm - 大字符串的快速字符串搜索算法

python - Pandas 数据框图

python - 如何使用 Selenium 在非安全页面上绕过消息 -"your connection is not private"?

java - 在 List 中使用通配符时出现编译时错误