Alec
Alec

Reputation: 4472

How to iterate over names and values in Julia NamedTuple?

E.g. if I have:

t = (
  a = 1:5,
  b = 2:6,
  c = 3:7,
)

And I'd like:

(
  a = 15,
  b = 20,
  c = 25,
)

What's an idiomatic way to accomplish this?

Upvotes: 0

Views: 994

Answers (3)

DNF
DNF

Reputation: 12654

I guess you want

julia> map(sum, t)
(a = 15, b = 20, c = 25)

Upvotes: 5

Andrej Oskin
Andrej Oskin

Reputation: 2332

You can also use good old map:

julia> map(x -> length(x) * (first(x) + 2), t)
(a = 15, b = 20, c = 25)

Upvotes: 0

longemen3000
longemen3000

Reputation: 1313

i don't know how to pass from 1:5 to 15, but if you allow me to invent such function, then, you could do:

julia> NamedTuple(k=>length(v)*(first(v)+2) for (k,v) in pairs(t))
(a = 15, b = 20, c = 25)

Upvotes: 2

Related Questions