修改列表元素

时间:2010-08-24 18:26:31

标签: python

如何修改以下列表:

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

这样的事情:

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

非常感谢提前。

2 个答案:

答案 0 :(得分:1)

看起来你想要压缩作为外部列表成员的元组?

试试这个:

>>> 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)]
>>> 

希望它有所帮助: - )

答案 1 :(得分:0)

不是特定的解决方案,但是itertools库中有很多很好的配方:

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