【问题标题】:Python Extracting items from a sublist if they match an item in another list's sublist如果它们与另一个列表的子列表中的项目匹配,则Python从子列表中提取项目
【发布时间】:2018-02-05 04:13:51
【问题描述】:

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

我有两个子列表:

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)

输出:[]

【问题讨论】:

  • 您应该改为创建第三个列表。修改您正在迭代的列表通常是一个坏主意。创建第三个列表,然后根据您的匹配条件添加到其中。

标签: python list string-matching


【解决方案1】:

这是一种方法,方法是构建一个 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]
]

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 这将包括 listB 中每个子列表的第一项。您可能希望在附加到 la 之前删除第一项。
    • 这行得通!这里的双 for 循环和我上面的 for 循环有什么区别?
    • 这类似于Selection_sort,但只是选择然后将B的元素放入A。listA的每个元素都应该与listB的每个元素进行比较。
    猜你喜欢
    • 2022-01-22
    • 2015-05-25
    • 1970-01-01
    • 2010-10-28
    • 2021-09-16
    • 1970-01-01
    • 2020-05-06
    • 2021-07-12
    • 2019-10-13
    相关资源
    最近更新 更多