使用嵌套列表连接列表

时间:2018-03-01 13:15:32

标签: python

a = [1, 2]
b = [[5,6], [7,8]]
c = list(zip(a, b))
print("c zipped:", c)
i = 0
lenghta = len(a)
c = []
while i < lengtha:
    temp_list = [a[i], b[i]]
    c.append(temp_list)
    i += 1
print("c: ", c)

输出:

c zipped: [(1, [5, 6]), (2, [7, 8])] c:  [[1, [5, 6]], [2, [7, 8]]]

我期待的是:

[[1, 5, 6], [2, 7, 8]]

4 个答案:

答案 0 :(得分:1)

这似乎过于复杂。试试这个,使用list comprehension

a = [1, 2]
b = [[5,6], [7,8]]

c = [[x] + b[i] for i, x in enumerate(a)]

答案 1 :(得分:1)

我知道这不是zip(),但您可以这样做:

c = []
for i in range(len(a)):
    c.append([a[i], b[i]])

答案 2 :(得分:1)

使用php.inizip

list comprehension

答案 3 :(得分:1)

你也可以使用itertools.chain

>>> from itertools import chain
>>> a = [1, 2]
>>> b = [[5,6], [7,8]]
>>> c = [list(chain([x], y)) for (x, y) in zip(a, b)]
>>> c
[[1, 5, 6], [2, 7, 8]]