且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中从两个列表创建(嵌套)列表

更新时间:2023-11-28 16:50:28

使用内置的zip函数.这正是您想要的.从python手册中:

Use the builtin zip function. It's exactly what you want. From the python manuals:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

或者,如果您要使用列表列表而不是元组列表,则可以将zip与列表理解一起使用:

Or if you want a list of lists, instead of a list of tuples, you use zip with a list comprehension:

>>> zipped = [list(t) for t in zip(x, y)]
>>> zipped
[[1, 4], [2, 5], [3, 6]]