简体   繁体   中英

Python: How to create 2D array using existing lists

I have been trying to resolve this issue.

I have 3 lists

dev = ['Alex', 'Ashley', 'Colin']
phone = ['iPhone', 'Nexus', 'Nokia']
carrier = ['ATT', 'T-Mobile', 'MegaFon']

Is this a pythonic way to create a new 2D array like this:

matrix = [['Alex', 'iPhone', 'ATT'], ['Ashley','Nexus','T-Mobile'], ['Colin', 'Nokia', 'MegaFon']]

Thank you

I think you want:

>>> zip(dev, phone, carrier)
[('Alex', 'iPhone', 'ATT'),
 ('Ashley', 'Nexus', 'T-Mobile'),
 ('Colin', 'Nokia', 'MegaFon')]

See zip documentation .

If you need a list of lists (instead of a list of tuples in Python 2, or an iterator in Python 3), use Padraic's suggestion: [list(x) for x in zip(dev, phone, carrier)] .

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