Gabriel Weich
Gabriel Weich

Reputation: 264

Join tuples inside list

I have:

mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]

I need one list with the letters and one with the numbers, like this:

(['a', 'b', 'c', 'd'], [1, 2, 3])

I have made some efforts, but I could just get one list with the letters, not both:

answer = [item for sublist in mylist for item in sublist[0]]
#returns ['a', 'b', 'c', 'd']

Upvotes: 1

Views: 74

Answers (3)

yatu
yatu

Reputation: 88236

Here's a simple alternative using zip and itertools.chain:

from itertools import chain
[list(chain.from_iterable(i)) for i in zip(*mylist)]
# [['a', 'b', 'c', 'd'], [1, 2, 3]]

Upvotes: 3

Austin
Austin

Reputation: 26039

zip works as well:

tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1])))

Code:

mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]

print(tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1]))))
# (['a', 'b', 'c', 'd'], [1, 2, 3])

Upvotes: 2

Max
Max

Reputation: 739

answer = [[item for sublist in mylist for item in sublist[i]] for i in range(2)]

Just need to iterate through your sublist :)

Upvotes: 6

Related Questions