0

How can I modify the list below:

[('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))]

into something like this:

[('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)]

Many thanks in advance.

DGT
  • 2,604
  • 13
  • 41
  • 60
  • 3
    What did you try? Please post some code showing (1) what the "modification" is and (2) what you tried to achieve this. – S.Lott Aug 24 '10 at 18:28
  • 1
    Duplicate: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python ? – cji Aug 24 '10 at 18:32
  • That's an example, but can you give general description of why and how you to modify the tuples within the list? E.g. _For element tuple within the list, it should convert / "flatten" any tuples contained within_. I _think_ that describes what you've shown, but I cannot be sure. – mctylr Aug 24 '10 at 18:33

2 Answers2

1

It looks like you want to flatten the tuples that are members of the outer list?

Try this:

>>> def flatten(lst):
    return sum( ([x] if not isinstance(x, (list, tuple)) else flatten(x)
             for x in lst), [] )

>>> def modify(lst):
    return [tuple(flatten(x)) for x in lst]

>>> x = [('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))]
>>> modify(x)
[('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)]
>>> 

Hope it helps :-)

Paddy3118
  • 4,704
  • 27
  • 38
0

Not a specific solution, but there are a lot of great recipes in the itertools library:

http://docs.python.org/library/itertools.html

NorthIsUp
  • 17,502
  • 9
  • 29
  • 35