Julia:如何根据具有特定值的类型字段访问类型数组中的元素

Posted

技术标签:

【中文标题】Julia:如何根据具有特定值的类型字段访问类型数组中的元素【英文标题】:Julia:How to access an element in an array of a type based on the type field with specific value 【发布时间】:2017-01-26 11:09:20 【问题描述】:

我有一个自定义类型的数组,称为links,其元素的类型为Link

type Link
    first::Int64
    second::Int64
    value::ArrayFloat64,1
end

,而且对于linkstypeof(links)VectorLink

正如您可能已经猜到的那样,这是我拥有的图形定义的一部分,其中包括边,first 指的是一个端点,second 指的是另一个端点。我要做的是在links 中选择linkvalue,其中端点first 等于特定的节点号,我们称之为vertex_id。 所以简而言之,我想要以下内容:

value of all those in links, whose .first == vertex_id.

P.S,我知道对于常规类型的 DataFrame,我可以说

df[df[:col1] .== x,:col2]

但是对于自定义类型的数组是否有类似的方法?

【问题讨论】:

我意识到我可以理解:[x.value for x in links if x.first == vertex_id] 但有更好的方法吗? 列表理解确实是您最好的选择。没有比这更简洁、高效和优雅的了。 【参考方案1】:

. 广播语法与:getfield 将是另一种选择(可能更类似于您可以使用 DataFrames 执行的操作):

getfield.(links,[:value])[getfield.(links, [:first]).==vertex_id]

但是您建议的列表理解解决方案可能更优雅。

[x.value for x in links if x.first == vertex_id]

【讨论】:

【参考方案2】:

我意识到我可以理解:

[x.value for x in links if x.first == vertex_id] 

【讨论】:

以上是关于Julia:如何根据具有特定值的类型字段访问类型数组中的元素的主要内容,如果未能解决你的问题,请参考以下文章