Convert list of tuples to list?

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

How do I convert

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

to

[1, 2, 3]
相关标签:
11条回答
  • 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)
    
    0 讨论(0)
  • 2020-12-02 13:44

    @Levon's solution works perfectly for your case.

    As a side note, if you have variable number of elements in the tuples, you can also use chain from itertools.

    >>> a = [(1, ), (2, 3), (4, 5, 6)]
    >>> from itertools import chain
    >>> list(chain(a))
    [(1,), (2, 3), (4, 5, 6)]
    >>> list(chain(*a))
    [1, 2, 3, 4, 5, 6]
    >>> list(chain.from_iterable(a)) # More efficient version than unpacking
    [1, 2, 3, 4, 5, 6]
    
    0 讨论(0)
  • 2020-12-02 13:44

    In these situations I like to do:

    a = [(1,), (2,), (3,)]
    new_a = [element for tup in a for element in tup]
    

    This works even if your tuples have more than one element. This is equivalent to doing this:

    a = [(1,), (2,), (3,)]
    new_a = []
    for tup in a:
        for element in tup:
            new_a.append(element)
    
    0 讨论(0)
  • 2020-12-02 13:47

    One Liner yo!

    list(*zip(*[(1,), (2,), (3,)]))
    
    0 讨论(0)
  • 2020-12-02 13:49

    Using simple list comprehension:

    e = [(1,), (2,), (3,)]
    [i[0] for i in e]
    

    will give you:

    [1, 2, 3]
    
    0 讨论(0)
提交回复
热议问题