【问题标题】:How to collect list of tuples into one tuple in Python? [duplicate]如何在 Python 中将元组列表收集到一个元组中? [复制]
【发布时间】:2014-06-09 11:13:22
【问题描述】:

我认为这应该是不费吹灰之力,但我有点迷路了。如果我有一个元组列表:

l = [(1, 2), (3, 4), (5, 6)]

如何将元组中的所有值放入一个列表中,以便结果如下:

[1, 2, 3, 4, 5, 6]

我想我需要使用列表推导,但我不确定如何......欢迎所有提示!

【问题讨论】:

    标签: python list tuples list-comprehension


    【解决方案1】:
    import itertools
    
    l = [(1, 2), (3, 4), (5, 6)]
    
    print list(itertools.chain(*l))
    

    print list(itertools.chain.from_iterable(l))
    
    
    
    #output =[1, 2, 3, 4, 5, 6]
    

    【讨论】:

    • .chain(*l) 正是 chain.from_iterable(l) 的用途(并且应该被首选)......
    • @JonClements 谢谢
    • 你也可以这样试试:list = [] for x in l: for y in x: list.append(y)
    猜你喜欢
    • 2013-02-22
    • 2015-10-30
    • 2017-07-30
    • 2022-10-08
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2019-12-25
    相关资源
    最近更新 更多