首页 > 解决方案 > 使用 map() 将具有多个变量的函数应用于列表的最简洁方法?

问题描述

我有一个具有多个输入变量的函数。对于特定情况,只有一个输入变量正在变化,是否可以使用映射应用此函数而无需列出不变变量?

例如:

# Example multiple variable input function
def Example_Function(x,y):
    return x**2+y**2

# Example List changing variable, x
List_of_x = [x for x in range(0,100)]

# Non-varying y
y = 4

# The naive version of the application (doesn't work)
Naive_Result_of_map_application = list(map(Example_Function, List_of_x, [y]))

# The result we want where we have to make a list of y ([y for i in range(0,100)])
Result_of_map_application = list(map(Example_Function, List_of_x, [y for i in range(0,100)]))

那么,有没有一种方法可以Result_of_map_application不用做[y for i in range(0,100)]呢?

标签: pythonvectorization

解决方案


我个人会取消map. 如果您不想y更改,我只是不会将其放在期望更改数据的上下文中。列表理解在这里工作正常:

Result_of_map_application = [Example_Function(x, y) for x in List_of_x]

推荐阅读