我有两个序列如下
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']]
答案 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))])