Reputation: 35
I apologize for the confusing title. I'm wondering what's the best way to compare two lists of sublists, and if an item in a sublist matches an item in the other list's sublist, the former list gets extended with the latter's items. I know this sounds very confusing, so here are the details:
I have two lists of sublists:
listA = [['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']]
listB = [['z', 7, 8, 9], ['x', 1, 2, 3], ['y', 4, 5, 6]]
Now I would like to extend listA
such that it contains the values in listB
if the first item in listA
's sublist matches that of listB
's sublists. So essentially, the end result should be the following:
listA = [['x', 'apple', 'orange', 1, 2, 3], ['y', 'cat', 'dog', 4, 5, 6], ['z', 'house', 'home', 7, 8, 9]]
Here's what I've tried:
for (sublistA, sublistB) in zip(listA, listB):
if sublistA[0] == sublistB[0]:
sublistA.extend(sublistB[1], sublistB[2], sublistB[3])
However, it seems like the code fails at the if statement. When I print listA, all I get is its original items:
>>> print(listA)
[['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']]
Why is it that the if statement isn't working? And what methods are available to do this matching followed by extraction of items?
Edit: As per idjaw's suggestion, I created a third list and tried doing the above for it again. However, I seem to be getting back an empty list as the if statement seems to not work again. Here's the code:
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)
Output: []
Upvotes: 3
Views: 1496
Reputation: 400
maybe your code could be this
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)
Upvotes: 0
Reputation: 49812
Here is one way of doing that by building a dict to allow easier lookup to the lists to add to:
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]
]
Upvotes: 3