简体   繁体   中英

Convert one-dimensional lists to multi-dimensional lists

For example, I have two lists

a = [1,2,3]
b = [4,5,6]

I want to make a list c which in format of

c = [[1,4],[2,5],[3,6]]

Since I am new to Python, Can anyone help me. Thank you.

Use zip (the example code is Python 2 style):

a = [1, 2, 3]
b = [4, 5, 6]
print zip(a, b)
# [(1, 4), (2, 5), (3, 6)]

Python 3 style:

a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b)))
# [(1, 4), (2, 5), (3, 6)]

If you actually want internal lists instead of tuples you can use:

a = [1,2,3]
b = [4,5,6]
c = [list(result) for result in zip(a,b)]
# c = [[1,4],[2,5],[3,6]] 
a = [1,2,3]
b = [4,5,6]
c = zip(a,b)
c = [list(k) for k in c]

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