开发者

python array_walk() alternative

开发者 https://www.devze.com 2023-03-18 04:55 出处:网络
开发者_StackOverflowi have a list that looks like this: list = [1,2,3,4] I would like to add 12 to each value. In PHP you can use array_walk to process each item in the array. Is there a similar fu
开发者_StackOverflow

i have a list that looks like this:

list = [1,2,3,4]

I would like to add 12 to each value. In PHP you can use array_walk to process each item in the array. Is there a similar function or easier way than doing a for loop such as:

for i in list:

Thanks


Use list comprehensions. Try this:

list = [i+12 for i in list]


my_list = [e+12 for e in my_list]

or:

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


alist = map(lambda i: i + 12, alist)

Update: @Daenyth says in the comments that this is slower than a list comprehension because of the function call overhead of using lambda. It looks like they're right, here are the stats from my machine (Macbook Air, 1.6GHz Core Duo, 4GB, Python 2.6.1):

Script:

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()

Results:

         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)
0

精彩评论

暂无评论...
验证码 换一张
取 消