我有两个相同长度的列表
a = [[1,2], [2,3], [3,4]]
b = [[9], [10,11], [12,13,19,20]]
Run Code Online (Sandbox Code Playgroud)
并希望将它们结合起来
c = [[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]]
Run Code Online (Sandbox Code Playgroud)
我是这样做的
c= []
for i in range(0,len(a)):
c.append(a[i]+ b[i])
Run Code Online (Sandbox Code Playgroud)
但是,我从R使用以避免for循环,而zip和itertools之类的替代品不会生成我想要的输出.有没有办法做得更好?
编辑: 谢谢你的帮助!我的清单有300,000个组件.解决方案的执行时间是
[a_ + b_ for a_, b_ in zip(a, b)]
1.59425 seconds
list(map(operator.add, a, b))
2.11901 seconds
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 12
Python有一个内置zip函数,我不确定它与R的相似程度,你可以像这样使用它
a_list = [[1,2], [2,3], [3,4]]
b_list = [[9], [10,11], [12,13]]
new_list = [a + b for a, b in zip(a_list, b_list)]
Run Code Online (Sandbox Code Playgroud)
[ ... for ... in ... ]如果你想了解更多,语法称为列表理解.
>>> help(map)
map(...)
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
Run Code Online (Sandbox Code Playgroud)
如您所见,map(…)可以将多个iterables作为参数.
>>> import operator
>>> help(operator.add)
add(...)
add(a, b) -- Same as a + b.
Run Code Online (Sandbox Code Playgroud)
所以:
>>> import operator
>>> map(operator.add, a, b)
[[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13]]
Run Code Online (Sandbox Code Playgroud)
请注意,在Python 3中默认map(…)返回一个生成器.如果您需要随机访问,或者您想多次迭代结果,那么您必须使用list(map(…)).
| 归档时间: |
|
| 查看次数: |
5701 次 |
| 最近记录: |