Creating a Python list from a list of tuples

前端 未结 6 1890
一个人的身影
一个人的身影 2021-01-16 17:57

If I have, for example, a list of tuples such as

a = [(1,2)] * 4

how would I create a list of the first element of each tuple? That is,

6条回答
  •  日久生厌
    2021-01-16 18:29

    Use a list comprehension:

    >>> a = [(1,2)] * 4
    >>> [t[0] for t in a]
    [1, 1, 1, 1]
    

    You can also unpack the tuple:

    >>> [first for first,second in a]
    [1, 1, 1, 1]
    

    If you want to get fancy, combine map and operator.itemgetter. In python 3, you'll have to wrap the construct in list to get a list instead of an iterable:

    >>> import operator
    >>> map(operator.itemgetter(0), a)
    
    >>> list(map(operator.itemgetter(0), a))
    [1, 1, 1, 1]
    

提交回复
热议问题