【问题标题】:How to convert array of named tuples to named tuple of arrays?如何将命名元组数组转换为数组命名元组?
【发布时间】:2023-03-29 18:22:01
【问题描述】:

如果我有一个命名元组数组:

[(a=1,b=1),
 (a=2,b=4),
 (a=3,b=9)]

我想要一个命名的数组元组:

(a=[1,2,3], b=[1,4,9])

有没有简单的方法来做到这一点?最好是偷懒或不抄袭。

【问题讨论】:

标签: arrays tuples julia


【解决方案1】:

这可以通过LazyArrays.jl 来实现。

julia> using LazyArrays

julia> xs = fill((a=1,b=2), 1024);

julia> using BenchmarkTools

julia> @btime (a = LazyArray(@~ getproperty.($xs, :a)), b = LazyArray(@~ getproperty.($xs, :b)))
  10.988 ns (2 allocations: 32 bytes)

julia> (a = LazyArray(@~ getproperty.(xs, :a)), b = LazyArray(@~ getproperty.(xs, :b))) == (a=getproperty.(xs, :a), b=getproperty.(xs, :b))
true

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多