开发者

Any way to zip to list of lists?

开发者 https://www.devze.com 2023-03-25 05:30 出处:网络
Alright, so I have two lists that look like this listx = [2, 4, 5, 9, 11] listy = [3, 5, 9, 12, 14] Right now, when I do zip, I get this

Alright, so I have two lists that look like this

listx = [2, 4, 5, 9, 11]
listy = [3, 5, 9, 12, 14]

Right now, when I do zip, I get this

listz = zip(listx, listy)
listz = [(2,3), (4,5), (5,9), (9, 12), (11,14)]

Is there any way to make this a l开发者_运维问答ist of lists instead of an array, like so

listz = [[2,3], [4,5], [5,9], [9,12], [11,14]]

Thanks!


You can use a comprehension:

listz = [list(i) for i in zip(listx, listy)]

or generator expression:

listz = (list(i) for i in zip(listx, listy))


Use map to convert the tuples to lists.

map(list, zip(listx, listy))


Use a list comprehension, and use izip to avoid creating an intermediary list.

import itertools

listz = [list(z) for z in itertools.izip(listx, listy)]


>>> from itertools import izip, imap
>>> listx = [2, 4, 5, 9, 11]
>>> listy = [3, 5, 9, 12, 14]
>>> listz = list(imap(list, izip(listx, listy)))
>>> listz
[[2, 3], [4, 5], [5, 9], [9, 12], [11, 14]]
0

精彩评论

暂无评论...
验证码 换一张
取 消