modifying list elements
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,开发者_StackOverflow社区 7, 8, 9)]
Many thanks in advance.
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 :-)
Not a specific solution, but there are a lot of great recipes in the itertools library:
http://docs.python.org/library/itertools.html
精彩评论