Python从子列表中提取与另一个列表中的项匹配的项';s子列表
我为这个令人困惑的标题道歉。我想知道比较两个子列表的最佳方法是什么,如果子列表中的一个项目与另一个列表的子列表中的一个项目匹配,则前者的列表将扩展为后者的项目。我知道这听起来很让人困惑,下面是详细信息: 我有两个子列表:Python从子列表中提取与另一个列表中的项匹配的项';s子列表,python,list,string-matching,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 = [['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)
输出:
[]
也许您的代码可能是这样的
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)
以下是一种方法,通过构建dict,可以更轻松地查找要添加到的列表: 代码: 测试代码: 结果:
您应该创建第三个列表。修改正在迭代的列表通常不是一个好主意。创建第三个列表,然后根据匹配条件添加到其中。这将包括listB中每个子列表的第一项。您可能希望在附加到la之前删除第一项。这很有效!这里的double for循环和我上面的for循环有什么区别?类似,但只需选择然后将B的元素放入A。listA的每个元素都应该与listB的每个元素进行比较。
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]
]