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

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

type Link
    first::Int64
    second::Int64
    value::Array{Float64,1}
end

,而且对于linkstypeof(links)Vector{Link}

正如您可能已经猜到的那样,这是我拥有的图形定义的一部分,其中包括边,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] 但有更好的方法吗?
  • 列表理解确实是您最好的选择。没有比这更简洁、高效和优雅的了。

标签: types julia composite-types


【解决方案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] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      相关资源
      最近更新 更多