python - 使用 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)]
呢?
解决方案
我个人会取消map
. 如果您不想y
更改,我只是不会将其放在期望更改数据的上下文中。列表理解在这里工作正常:
Result_of_map_application = [Example_Function(x, y) for x in List_of_x]
推荐阅读
- c# - 如何从实时文件中读取行?
- c# - 使用自定义渲染器 UWP 打开 SwipeView
- python - 以编程方式在脚本中找到调用函数的行
- twilio - 我应该使用哪些 Prometheus 函数在 Grafana 中设置关于总请求与成功请求之间比率的警报?
- javascript - 使用 JavaScript 命名空间对象构建和发布 npm 包
- c# - Xamarin Android.Content.Res.Resources + NotFoundException
- node.js - 在特定值之后更新整个文档
- javascript - 是否可以在 JS 中向 html 元素添加一些类并在一行中删除一些其他类?
- filestream - SQL Server 数据库的还原失败并显示“FILESTREAM 功能已禁用,尽管它已启用
- reactjs - jest.fn(implementationCallback) 和 jest.fn().mockImplementation(implementationCallback) 之间的区别