list comprehension结合2个列表

时间:2017-09-25 18:10:13

标签: python python-2.7 list

我有两个序列如下

t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']

如何使用列表推导来修改t如下: -

t = [[1,2,3,'a'],[4,5,6,'b'],[7,8,9,'c']]

3 个答案:

答案 0 :(得分:4)

您可以使用zip获取相应的元素对,并且从那里只需要加入:

>>> t = [[1,2,3],[4,5,6],[7,8,9]]
>>> alpha = ['a','b','c']
>>> [x[0] + [x[1]] for x in zip(t,alpha)]
[[1, 2, 3, 'a'], [4, 5, 6, 'b'], [7, 8, 9, 'c']]

答案 1 :(得分:2)

使用zip

t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
new_list = [a+[b] for a, b in zip(t, alpha)]

输出:

[[1, 2, 3, 'a'], [4, 5, 6, 'b'], [7, 8, 9, 'c']]

答案 2 :(得分:2)

迭代指数:

t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
print([t[i] + [alpha[i]] for i in range(len(alpha))])