Creating a Python list from a list of tuples

前端 未结 6 1843
一个人的身影
一个人的身影 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:48

    There are several ways:

    >>> a = [(1,2)] * 4
    
    >>> # List comprehension
    >>> [x for x, y in a]
    [1, 1, 1, 1]
    
    >>> # Map and lambda
    >>> map(lambda t: t[0], a)
    [1, 1, 1, 1]
    
    >>> # Map and itemgetter
    >>> import operator
    >>> map(operator.itemgetter(0), a)
    [1, 1, 1, 1]
    

    The technique of using map fell out of favor when list comprehensions were introduced, but now it is making a comeback due to parallel map/reduce and multiprocessing techniques:

    >>> # Multi-threading approach
    >>> from multiprocessing.pool import ThreadPool as Pool
    >>> Pool(2).map(operator.itemgetter(0), a)
    [1, 1, 1, 1]
    
    >>> # Multiple processes approach
    >>> from multiprocessing import Pool
    >>> def first(t):
            return t[0]
    >>> Pool(2).map(first, a)
    [1, 1, 1, 1]
    

提交回复
热议问题