I have two lists of lists – i.e.
[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]
as well as
[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]
Lets call them list1 and list2
I want to merge list1 and list2, but ONLY when (note, this is pseudocode, trying to figure out how to program this in Python)
x[0] in list1 == x[0] in list2
I’m not sure how to write this out.
By merge I mean (pseudocode)
list[x] = list1[x] + list2[x] while x[0] in list1 == x[0] in list2
Output desired:
[['1', 'expired', 'test', '0', '1', 'Andrew', 'Alexander'], ['31', 'active', 'test', '1', '31', 'John', 'Smith']]
The only critical point is that not all of the x[0]’s are going to match up perfectly.
Using agf’s idea of employing a collections.defaultdict, this in O(m+n) where
mandnare the lengths of the lists.yields
In the comments the OP says the desired output is
(this is different than the desired output posted in the original question.)
Then:
This is one of the few times I’ve found using setdefault more convenient than
collections.defaultdict.