我们说我有名单
[[1,2,3], [4,5,6]]
我想为每个元素添加5个。
然后新列表将[[6,7,8],[9,10,11]]作为答案。
def add(num, list):
答案 0 :(得分:5)
只需执行嵌套列表理解(并且不要使用list
作为名称,它会覆盖内置函数):
def add(num, lst):
return [[item+num for item in sub] for sub in lst]
演示:
>>> test = [[1, 2, 3], [4, 5, 6]]
>>> add(5, test)
[[6, 7, 8], [9, 10, 11]]
答案 1 :(得分:2)
add
模块operator
个运算符
>>> from operator import add
>>> add(7, 5)
12
functool
允许按partial
>>> from functools import partial
>>> add5 = partial(add, 5)
>>> add5(7)
12
map
在简单的sublst上应用add5
>>> sublst = [1,2,3]
>>> map(add5, sublst)
[6, 7, 8]
>>> lst = [[1,2,3], [4,5,6]]
>>> [map(add5, sublst) for sublst in lst]
[[6, 7, 8], [9, 10, 11]]
使用已准备好的函数add5
>>> %timeit [map(add5, sublst) for sublst in lst]
1000000 loops, best of 3: 1.23 µs per loop
使用建议的答案之一:
>>> [[item+5 for item in sub] for sub in lst]
[[6, 7, 8], [9, 10, 11]]
>>> %timeit [[item+5 for item in sub] for sub in lst]
1000000 loops, best of 3: 658 ns per loop
在我们需要的时候创建add5
:
>>> [map(partial(add, 5), sublst) for sublst in lst]
[[6, 7, 8], [9, 10, 11]]
>>> %timeit [map(partial(add, 5), sublst) for sublst in lst]
1000000 loops, best of 3: 1.5 µs per loop
将num
添加到变量中:
>>> num = 5
>>> [map(partial(add, num), sublst) for sublst in lst]
[[6, 7, 8], [9, 10, 11]]
>>> def add2lst(num, lst):
... return [map(partial(add, num), sublst) for sublst in lst]
...
和测试,它的工作原理
>>> add2lst(5, lst)
[[6, 7, 8], [9, 10, 11]]
>>> timeit.timeit("[[item+5 for item in sub] for sub in lst]", setup="from functools import partial;from operator import add;lst=[[1,2,3],[4,5,6]]", number=rep)
6.1195290088653564
>>> timeit.timeit("[map(partial(add, 5), sublst) for sublst in lst]", setup="from functools import partial;from operator import add;lst=[[1,2,3],[4,5,6]]", number=rep)
14.058987140655518
智能概念使用运算符和部分增加的执行复杂性,导致此解决方案的速度比简单解决方案慢两倍。
所以:“保持简单”
答案 2 :(得分:1)
如果您愿意使用Numpy
:
import numpy as np
np.array([[1,2,3], [4,5,6]]) + 5
将添加5
元素返回:
array([[ 6, 7, 8],
[ 9, 10, 11]])
答案 3 :(得分:0)
map()
并且列表理解完成了这项工作:
def add(num, lst):
return [map(lambda x: x + num, l) for l in lst]