我有一个看起来像这样的列表:蟒蛇array_walk()替代
list = [1,2,3,4]
我想补充12到每个值。在PHP中,您可以使用array_walk处理数组中的每个项目。是否有一个类似的功能或更简单的方法不是做一个for循环,例如:
for i in list:
感谢
我有一个看起来像这样的列表:蟒蛇array_walk()替代
list = [1,2,3,4]
我想补充12到每个值。在PHP中,您可以使用array_walk处理数组中的每个项目。是否有一个类似的功能或更简单的方法不是做一个for循环,例如:
for i in list:
感谢
my_list = [e+12 for e in my_list]
或:
for i in range(len(my_list)):
my_list[i] += 12
使用list comprehensions。试试这个:
list = [i+12 for i in list]
alist = map(lambda i: i + 12, alist)
更新:@Daenyth说,在评论,这是不是因为使用lambda的函数调用的开销清单理解慢。看起来他们是对的,这里是从我的机器(Macbook Air的,1.6GHz的Core Duo处理器,4GB,Python的2.6.1)的统计数据:
脚本:
import hotshot, hotshot.stats
def list_comp(alist):
return [x + 12 for x in alist]
def list_map(alist):
return map(lambda x: x + 12, alist)
def run_funcs():
alist = [1] * 1000000
result = list_comp(alist)
result = list_map(alist)
prof = hotshot.Profile('list-manip.prof')
result = prof.runcall(run_funcs)
stats = hotshot.stats.load('list-manip.prof')
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats()
结果:
1000003 function calls in 0.866 CPU seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.465 0.465 0.683 0.683 untitled.py:6(list_map)
1000000 0.218 0.000 0.218 0.000 untitled.py:7(<lambda>)
1 0.157 0.157 0.157 0.157 untitled.py:3(list_comp)
1 0.025 0.025 0.866 0.866 untitled.py:9(run_funcs)
0 0.000 0.000 profile:0(profiler)
这很可能是最快的方法。 –
@Gerardo Marset:实际上它比listcomp慢,因为函数查找的开销。另一篇文章中的一些人对它进行了计时。 – Daenyth