Home > Software design >  Combining the elements at a given index in a list of tuples with another list to form pairs
Combining the elements at a given index in a list of tuples with another list to form pairs

Time:05-04

I have two lists:

x = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
y = ['A', 'B', 'C']

I want to take every first item of each tuple in the first list and combine it with the second list to look like this:

output = [(1, 'A'), (4, 'B'), (7, 'C')]

Also in both list I'll have few thousands of elements, so I would appreciate solution that will be as fast as possible.

CodePudding user response:

You can use a simple list comprehension with zip:

output = [(a[0], b) for a, b in zip(x, y)]

you can also preprocess x with operator.itemgetter:

from operator import itemgetter
output = list(zip(map(itemgetter(0), x), y))

output:

[(1, 'A'), (4, 'B'), (7, 'C')]

CodePudding user response:

output = [(x[i][0],y[i]) for i in range(len(x))]

CodePudding user response:

Try:

x = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
y = ['A', 'B', 'C']

output = [ (i[0], j) for i, j in zip(x, y) ]

print(output)

[(1, 'A'), (4, 'B'), (7, 'C')]

CodePudding user response:

You can do this with zip():

list(zip(list(zip(*x))[0], y))

Output:

[(1, 'A'), (4, 'B'), (7, 'C')]
  • Related