我有
g = [[1], [2], [3], [4], [5], [6]]
c = [[9], [8], [7], [6], [5], [4]]
我需要得到
t = [[1,9], [2,8], [3,7], [4,6], [5,5], [6,4]]
请帮帮我
答案 0 :(得分:5)
使用此处的zip()
function来组合嵌套列表的元素:
t = [a + b for a, b in zip(g, c)]
演示:
>>> g = [[1], [2], [3], [4], [5], [6]]
>>> c = [[9], [8], [7], [6], [5], [4]]
>>> [a + b for a, b in zip(g, c)]
[[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4]]
使用iterative zip()
function from Python 3 / itertools
:
try:
from future_builtins import zip
except ImportError:
pass
t = [a + b for a, b in zip(g, c)]
只有在希望代码同时适用于Python 2和3时才需要try..except
。
答案 1 :(得分:0)
另一个没有zip的选项,使用list comprehension:
>>> g = [[1], [2], [3], [4], [5], [6]]
>>> c = [[9], [8], [7], [6], [5], [4]]
>>> result = [ [g[i][0], c[i][0]] for i in range(min([len(g), len(c)])) ]
>>> print(result)
[[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4]]
>>>
答案 2 :(得分:0)
你好,如果你使用的是Python 2.7,你可以使用zip
g = [[1], [2], [3], [4], [5], [6]]
c = [[9], [8], [7], [6], [5], [4]]
t = zip(g, c)
[([1], [9]), ([2], [8]), ([3], [7]), ([4], [6]), ([5], [5]), ([6], [4])]