简体   繁体   中英

How do I create a list of tuple elements

Lets say I have three list:

List1 = [1,2,3]
List2 = [4,5,6]
List3 = [7,8,9]

And now I want to create a new list with tuple elements, but use the data from my previous lists:

NewList = [(1,4,7), (2,5,6), (3,6,9)]

How can this be done?

All you need is zip :

>>> List1 = [1,2,3]
>>> List2 = [4,5,6]
>>> List3 = [7,8,9]
>>> zip(*(List1, List2, List3))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>

Also, you will notice that the third element of the second tuple is different. I think you have a typo in your question.

As an alternative answer if performance is important for you , i suggest use itertools.izip instead built-in zip() :

>>> l=[List1,List2,List3]
>>> from itertools import izip
>>> list(izip(*l))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

This is not the best way to do it, just as an alternative.

>>> NewList = []
>>> i = 0
>>> while i <= len(List1)-1 :
        NewList.append(tuple(j[i] for j in (List1, List2, List3)))
        i+=1
>>>NewList
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM