tags:

views:

120

answers:

3

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!

+4  A: 

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))
bluejeansummer
The list comprehension given by crescentfresh is shorter, but this is not exactly long, and for some people this will be easier to follow, especially beginners.
John Y
+10  A: 

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.

Crescent Fresh
Works for me perfectly. I got stuck with what was supposed to be easy for too long. Now I also understand what generators are all about, thanks!
@kon: I didn't use a generator. That is a list comprehension you see there: http://www.network-theory.co.uk/docs/pytut/ListComprehensions.html
Crescent Fresh
+1  A: 

(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'])
]
Federico Ramponi