有效地将参数传递给存储在列表或dicitonary

时间:2016-05-05 04:47:30

标签: python list function dictionary

比如说我有100个独特的功能(出于演示目的,我只有一个)

def calcs(x):
     return x**2 

这些100个独特的函数存储在列表或字典中(对存储这些函数的方法持开放态度)

import numpy as np
store_funcs = []
for i in np.arange(100):
     store_funcs.append(calcs)

现在我有一个包含100个数字的数组

nums = np.random.uniform(0,1, 100)

我想将nums的第一个元素传递给store_funcs中的第一个函数,并让它将nums的第二个元素返回给store_funcs中的第二个函数1}}等等......我的问题是,有没有一个更清洁(更快?)的方法来实现这个没有循环?

for i in np.arange(100):
     print store_funcs[i](nums[i])

同样欢迎其他有关如何实现这一目标的想法。 谢谢!

2 个答案:

答案 0 :(得分:1)

通常,在不知道正在执行的代码的性质的情况下优化代码非常困难。也就是说,这是一个班轮:

map(lambda x : x[0](x[1]), zip(store_funcs, nums))

这可能不会更快,但它是一行?

另一方面,如果你的功能是瓶颈,那么你可能想要查看诸如芹菜或其他异步执行库之类的东西。这样,你仍然会循环,但是在每次迭代中,你只花费时间将消息发送到某个队列以供工作池使用。

答案 1 :(得分:1)

看起来您的问题可以通过multiprocessing module

从某些并行性中受益
import multiprocessing as mp

# create a function that will execute our function + argument pair
def executor(*args):

    # assume args[0] is our function object and args[1] is the number
    return args[0](args[1])

# assume we have a list of functions called "funcs" and a list of numbers
# called "nums", and they are of equal length - use zip to pair them off
pairs = zip(funcs, nums) 

# create a multiprocessing pool
pool = mp.Pool()

# submit our list of function+argument pairs to the pool for execution
result_list = pool.map(executor, pairs)

# clean up
pool.join()
pool.close()

一些有用的链接:

Multiprocessing Pools
The zip builtin

很难回答原始问题,哪个数据结构更有意义,因为我们不知道你的实际函数和数字数组是如何生成的(我假设[并希望]它们并非都是硬编码的)或重复使用。如果你在这里描述的内容确实是两者的唯一用例,那么字典可能更有意义,因为它清楚地表达了每个函数和数字之间的1:1关系。

但是,字典和列表同样能够允许您以迭代方式执行函数+参数对,因此如果函数列表或数字数组在代码中的其他地方重用,我会坚持两个名单所以它们作为单独的实体存在仍然很清楚。