5

I have a "sparse array" like this

arr[1.5]=0.4, arr[3.5]=0.7, arr[7]=0.3

which is not really a sparse array since the keys are not all integers. This is like a hash table or associative array.

How can I convert arr into a list? I tried Normal[arr], but it won't work. I would like to be able to compute Total@arr, but first it needs to be converted to a normal list.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
dabd
  • 839
  • 4
  • 13

2 Answers2

9

This might be the general sort of operation you seek.

keyvalpairs = 
 DownValues[arr] /. Verbatim[HoldPattern][arr[k_]] :> k

(* Out[121]= {1.5 :> 0.4, 3.5 :> 0.7, 7 :> 0.3} *)
Daniel Lichtblau
  • 58,970
  • 2
  • 101
  • 199
8

Here is one way to do it:

{arr[1.5] = 0.4, arr[3.5] = 0.7, arr[7] = 0.3}
Total[DownValues[arr][[All, 2]]]
s0rce
  • 9,632
  • 4
  • 45
  • 78