Convert list of tuples to list?

后端 未结 11 1126
旧巷少年郎
旧巷少年郎 2020-12-02 12:54

How do I convert

[(1,), (2,), (3,)]

to

[1, 2, 3]
11条回答
  •  萌比男神i
    2020-12-02 13:39

    Here is another alternative if you can have a variable number of elements in the tuples:

    >>> a = [(1,), (2, 3), (4, 5, 6)]
    >>> [x for t in a for x in t]
    [1, 2, 3, 4, 5, 6]
    

    This is basically just a shortened form of the following loops:

    result = []
    for t in a:
        for x in t:
            result.append(x)
    

提交回复
热议问题