python array_walk() 替代方案

4 投票
3 回答
3918 浏览
提问于 2025-04-16 21:09

我有一个这样的列表:

list = [1,2,3,4]

我想给每个值加上12。在PHP中,你可以用array_walk这个函数来处理数组里的每一项。有没有类似的函数,或者比用for循环更简单的方法,比如:

for i in list:

谢谢

3 个回答

4

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)
4
my_list = [e+12 for e in my_list]

或者:

for i in range(len(my_list)):
    my_list[i] += 12
10

使用列表推导式。可以试试这个:

list = [i+12 for i in list]

撰写回答