kon
kon

Reputation:

Transforming nested list in Python

Assuming I have a structure like this:

a = [
('A',
 ['D',
  'E',
  'F',
  'G']),
('B',
 ['H']),
('C',
 ['I'])
]

How can I transform it into:

a = [
('A', 'D'),
('A', 'E'),
('A', 'F'),
('A', 'G'),
('B', 'H'),
('C', 'I'),
]

Thanks for your time!

Upvotes: 0

Views: 294

Answers (3)

Federico A. Ramponi
Federico A. Ramponi

Reputation: 47075

(Side comment) Why on earth did you indent like that? Isn't the following more readable?

a = [
('A', ['D', 'E', 'F', 'G']),
('B', ['H']),
('C', ['I'])
]

Upvotes: 1

Crescent Fresh
Crescent Fresh

Reputation: 116980

Try:

>>> a = [('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I'])]
>>> [(k,j) for k, more in a for j in more]
[('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I')]

This handles only one level of nesting of course.

Upvotes: 10

Cassie Meharry
Cassie Meharry

Reputation: 2683

Here's a simple solution:

data = [
('A',
  ['D',
  'E',
  'F',
  'G']),
('B',
  ['H']),
('C',
  ['I'])
]

result = []

for x in data:
    for y in x[1]:
        result.append((x[0], y))

Upvotes: 4

Related Questions