Creating a Python list from a list of tuples

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

    Assuming you have a list of tuples:

    lta = [(1,2), (2,3), (44,45), (37,38)]
    

    access the first element of each tuple would involve subscripting with [0], and visiting each tuple to extract each first element would involve a a list comprehension, which can be assigned to a variable as shown below:

    resultant_list = [element[0] for element in lta]
    >>> resultant_list
    [1, 2, 44, 37]
    

提交回复
热议问题