字典的向量化索引 [英] Vectorized indexing for a dictionary

查看:62
本文介绍了字典的向量化索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Julia中找到一种简洁的语法,以向量化的方式索引字典.在R中,我将执行以下操作:

I would like to find a succinct syntax in Julia for indexing a dictionary in a vectorized manner. In R, I would do the following:

dict <- c("a" = 1, "b" = 2)
keys <- c("a", "a", "b", "b", "a")
dict[keys]

在朱莉娅中,如果我有这样的dictkeys

In Julia, if I have a dict and keys like this,

dict = Dict(:a => 1, :b => 2)
keys = [:a, :a, :b, :b, :a]

然后我可以使用列表理解来达到预期的结果:

then I can achieve the desired result using a list comprehension:

julia> [dict[key] for key in keys]
5-element Array{Int64,1}:
 1
 1
 2
 2
 1

是否有更简洁的矢量化语法,类似于R语法?

Is there a more succinct vectorized syntax, similar to the R syntax?

推荐答案

getindex.(Ref(dict), keys)

您可以将其包装在Ref中,因此无需[].

You can wrap it in Ref so you don't need to [] it.

这篇关于字典的向量化索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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