将值附加到具有嵌套列表的列表 python

Append values to a list that has a nested list python

我有两个列表:

L1 = [[a,b,c],[d,e,f]]
L2 = [1,2]

我希望输出为:

L3 = [[[a,b,c],1], [[d,e,f],2]]

我该怎么做?

zip运算符试试这个

L1 = [['a','b','c'],['d','e',"f"]]
L2 = [1,2]
L3 = []
for (list1, list2) in zip(L1,L2):
    L3.append([list1, list2])
print(L3)

以下似乎可以解决问题:

def combine(L1, L2):
    return [[e1, e2] for e1, e2 in zip(L1, L2)]

L1 = [['a', 'b', 'c'], ['d', 'e', 'f']]
L2 = [1,2]
L3 = combine(L1, L2)

输出:

[[['a','b','c'],1], [['d','e','f'],2]]

您还可以使用列表理解,假设您的列表始终具有相同的大小:

L3 = [[L1[i], L2[i]] for i in range(len(L1))]
print(L3)

输出:

[[['a', 'b', 'c'], 1], [['d', 'e', 'f'], 2]]
from itertools import cycle

L1 = [['a','b','c'],['d','e','f']]
L2 = [1,2]

def do_something(L1,L2):
    combos = list(zip(L1,cycle(L2)))
    print(combos)
do_something(L1,L2)