使用带有关键字参数的 map() 函数 [英] Using map() function with keyword arguments

查看:20
本文介绍了使用带有关键字参数的 map() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试使用 map 函数的循环:

Here is the loop I am trying to use the map function on:

volume_ids = [1,2,3,4,5]
ip = '172.12.13.122'
for volume_id in volume_ids:
    my_function(volume_id, ip=ip)

有没有办法做到这一点?如果不是 ip 参数,那将是微不足道的,但我不确定如何处理.

Is there a way I can do this? It would be trivial if it weren't for the ip parameter, but I'm not sure how to deal with that.

推荐答案

使用 functools.partial():

from functools import partial

mapfunc = partial(my_function, ip=ip)
map(mapfunc, volume_ids)

partial() 创建一个新的可调用对象,除了传递给该新可调用对象的任何参数外,它还会将任何参数(包括关键字参数)应用于包装函数.

partial() creates a new callable, that'll apply any arguments (including keyword arguments) to the wrapped function in addition to whatever is being passed to that new callable.

这篇关于使用带有关键字参数的 map() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆