简体   繁体   English

修改列表元素

[英]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, 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: 这不是一个特定的解决方案,但是itertools库中有很多不错的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM