Home > Mobile >  How to combine two lists into a single list using python
How to combine two lists into a single list using python

Time:12-05

I've two lists comprising of multiple tuples inside them. I'm looking for a way to combine both the lists into a single list.

list 1 = [('mike','Company A','developer'),('steve','Company B','developer'),('tom','Company B','tester'),('jerry','Company A','tester')]

list 2 = [('mike','Company A','C  '),('steve','Company B','Python'),('tom','Company B','Automation'),('mike','Company A','Manual')]

Expected output:

list 3 = [('mike','Company A','developer','C  '),('steve','Company B','developer,'Python'),('tom','Company B','tester','Automation'),('mike','Company A','tester','Manual')

CodePudding user response:

Combining the two lists is easy:

list1   list2
# [('mike', 'Company A', 'developer'),
#  ('steve', 'Company B', 'developer'),
#  ('tom', 'Company B', 'tester'),
#  ('jerry', 'Company A', 'tester'),
#  ('mike', 'Company A', 'C  '),
#  ('steve', 'Company B', 'Python'),
#  ('tom', 'Company B', 'Automation'),
#  ('mike', 'Company A', 'Manual')]

Then sort them.

>>> sorted(list1   list2, key=lambda x: (x[0], x[1]))
# [('jerry', 'Company A', 'tester'),
#  ('mike', 'Company A', 'developer'),
#  ('mike', 'Company A', 'C  '),
#  ('mike', 'Company A', 'Manual'),
#  ('steve', 'Company B', 'developer'),
#  ('steve', 'Company B', 'Python'),
#  ('tom', 'Company B', 'tester'),
#  ('tom', 'Company B', 'Automation')]

Group them by the first two elements using itertools.groupby.

>>> groupby(sorted(list1   list2, key=lambda x: (x[0], x[1])), key=lambda x: (x[0], x[1]))
<itertools.groupby object at 0x7f77deb2f818>

Extract the third element from each value in each group using list comprehensions.

>>> [(k[0], k[1], [x[2] for x in v]) for k, v in groupby(sorted(list1   list2, key=lambda x: (x[0], x[1])), key=lambda x: (x[0], x[1]))]
# [('jerry', 'Company A', ['tester']),
#  ('mike', 'Company A', ['developer', 'C  ', 'Manual']),
#  ('steve', 'Company B', ['developer', 'Python']),
#  ('tom', 'Company B', ['tester', 'Automation'])]

From there it's just a matter of expanding thos lists out into each tuple.

CodePudding user response:

list3 = list1 list2

Concatenate two lists

  • Related