【问题标题】:How to put elements from a list to a list of list in Python 3?如何将列表中的元素放入 Python 3 中的列表列表中?
【发布时间】:2019-03-19 13:23:36
【问题描述】:

我试图将list2 中的元素放在list1 的每个嵌套列表中。这是我迄今为止尝试过的:

list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
store_1 = []
for x in list_1:
    for y in list_2:
        x.append(y)
        store_1.append(x)
print(store_1)

但是输出是:

[[0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100]]

输出应该是这样的:

[[0,1,100],[1,4,100], [2,3,100]]

如何修复我的代码以获得所需的输出?

【问题讨论】:

    标签: python python-3.x algorithm list nested


    【解决方案1】:

    使用zip

    例如:

    list_1 = [[0, 1], [1, 4], [2, 3]]
    list_2 = [100, 100, 100]
    store_1 = [x + [y] for x, y in zip(list_1, list_2)]
    print(store_1)
    

    输出:

    [[0, 1, 100], [1, 4, 100], [2, 3, 100]]
    

    【讨论】:

    • 这会变异 list_1... 我怀疑 OP 在 store_1 = [[*l1, l2] for l1, l2 in zip(list_1, list_2)] 之后
    【解决方案2】:

    不使用zip

    list_1 = [[0, 1], [1, 4], [2, 3]]
    list_2 = [100, 100, 100]
    [list_1[idx] + [x] for idx, x in enumerate(list_2)]
    
    > [[0, 1, 100], [1, 4, 100], [2, 3, 100]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2015-04-09
      • 2023-03-21
      相关资源
      最近更新 更多