Convert list of tuples to list?

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

How do I convert

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

to

[1, 2, 3]
相关标签:
11条回答
  • 2020-12-02 13:25

    You can also unpack the tuple in the list comprehension:

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

    will still give:

    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-02 13:28

    You can also use sum function as follows:

    e = [(1,), (2,), (3,)] 
    e_list = list(sum(e, ()))
    

    And it also works with list of lists to convert it into a single list, but you will need to use it as follow:

    e = [[1, 2], [3, 4], [5, 6]]
    e_list = list(sum(e, []))
    

    This will give you [1, 2, 3, 4, 5, 6]

    0 讨论(0)
  • 2020-12-02 13:31
    >>> a = [(1,), (2,), (3,)]
    >>> b = map(lambda x: x[0], a)
    >>> b
    [1, 2, 3]
    

    With python3, you have to put the list(..) function to the output of map(..), i.e.

    b = list(map(lambda x: x[0], a))
    

    This is the best solution in one line using python built-in functions.

    0 讨论(0)
  • 2020-12-02 13:34

    There's always a way to extract a list from another list by ...for...in.... In this case it would be:

    [i[0] for i in e]

    0 讨论(0)
  • 2020-12-02 13:35
    >>> a = [(1,), (2,), (3,)]
    >>> zip(*a)[0]
    (1, 2, 3)
    

    For a list:

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

    Using operator or sum

    >>> from functools import reduce ### If python 3
    >>> import operator
    >>> a = [(1,), (2,), (3,)]
    >>> list(reduce(operator.concat, a))
    [1, 2, 3]
    

    (OR)

    >>> list(sum(a,()))
    [1, 2, 3]
    >>> 
    

    If in python > 3 please do the import of reduce from functools like from functools import reduce

    https://docs.python.org/3/library/functools.html#functools.reduce

    0 讨论(0)
提交回复
热议问题