Julia:通过 map() 函数将关键字参数传递给函数 [英] Julia: Passing keyword arguments to function through the map() function

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

问题描述

我正在尝试使用 map() 将函数 quandl 应用于 (n x 1) 字符串数组.(http://quandljl.readthedocs.io/en/latest/get_data.html)

I am trying to use map() to apply the function quandl on an array of (n x 1) strings. (http://quandljl.readthedocs.io/en/latest/get_data.html)

但是,我希望传递的不仅仅是字符串作为函数的参数,例如 from = Date1to = Date2.我似乎无法找到一种方法让 map() 将函数应用于字符串数组,同时还传递关键字参数以将数据从 Date1 下载到 Date2.

However, I wish to pass on more than just the strings as arguments to the function, such as from = Date1 and to = Date2. I cannot seem to find a way to have map() apply the function on the array of strings while also passing the keyword arguments to download data from Date1 to Date2.

更普遍的问题是:如何使用 map() 将函数应用于多个元素,同时向该函数传递附加参数?

The more general question is: how can I use map() to apply a function on several elements while also passing additional arguments to this function?

推荐答案

您需要创建一个匿名函数,该函数使用适当的参数调用 quandl 并将其映射到您的数据上.由于我不太清楚您想如何调用 quandl,因此我将使用一个虚构的示例.假设 f 接受两个位置参数和一个关键字 k;假设您想将其应用于 v 的每个值,其中 2 作为第二个参数和 k = "abc".你会这样做:

You'll want to create an anonymous function that calls quandl with the appropriate arguments and map that over your data. Since I'm a little unclear on how you want to call quandl, I'll just use a made up example. Suppose f takes two positional arguments and a keyword k; suppose you want to apply it to each value of v with 2 as the second argument and k = "abc". You would do this like so:

map(x -> f(x, 2, k = "abc"), v)

如果匿名函数体很大或很复杂,你可能想使用 Julia 的 do-block 语法 并像这样编写计算:

If the anonymous function body is large or complicated, you may want to use Julia's do-block syntax and write the computation like this instead:

map(v) do x
    f(x, 2, k = "abc")
end

在这个例子中,这没有多大意义,但如果匿名函数是多行代码,那么这可能更可取.

In this example, this doesn't make much sense, but if the anonymous function is multiple lines of code, then this can be preferable.

这篇关于Julia:通过 map() 函数将关键字参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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