Creating a Python list from a list of tuples

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

    I recently found out about Python's zip() function. Another way to do what I want to do here is:

    list( zip( *a )[0] )
    

    tup_list = zip( list1, list2 ) interleaves two lists into a list of 2-tuples, but zip( *tup_list ) does the opposite, resulting in a list of a tuple of list1 and a tuple of list2.

提交回复
热议问题