【问题标题】:How to combine 2 list into pairs of nested list?如何将 2 个列表组合成一对嵌套列表?
【发布时间】:2020-06-01 01:18:42
【问题描述】:

所以,我有 2 个列表:

list1 = [1,2,3,4,5]
list2= [6,7,8,9,10]

想要的输出:

newlist = [[1,6],[2,7],[3,8],[4,9],[5,10]]

如何在 Python 中做到这一点?

【问题讨论】:

  • 您可以尝试:[*map(list,zip(list1,list2))]list(map(list,zip(list1,list2))),对于数组使用:np.column_stack((list1,list2))

标签: python-3.x pandas list


【解决方案1】:

使用zip,但输出的是元组列表,所以由list添加map

a = list(map(list, zip(list1, list2)))
print (a)
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

或者使用列表推导:

a = [list(x) for x in zip(list1, list2)]

【讨论】:

    【解决方案2】:

    使用 zip 功能

    list1 = [1,2,3,4,5]
    list2= [6,7,8,9,10]
    list3 = list(zip(list1, list2))
    print(list3)
    

    【讨论】:

    • 输出是元组列表,而不是列表列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2023-01-09
    • 2011-07-31
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多