admin管理员组

文章数量:1295883

given a dictionary that looks like this:

`a`b`c!((0;3); (1;4); enlist 2)

I'd like to find an elegant way to get the following list as a result: 

`a (index 0)
`b (index 1)
`c (index 2)
`a (index 3)
`b (index 4)

given a dictionary that looks like this:

`a`b`c!((0;3); (1;4); enlist 2)

I'd like to find an elegant way to get the following list as a result: 

`a (index 0)
`b (index 1)
`c (index 2)
`a (index 3)
`b (index 4)
Share Improve this question edited Feb 12 at 10:11 cillianreilly 2,0766 silver badges16 bronze badges asked Feb 12 at 9:39 kkudikkudi 1,6674 gold badges25 silver badges48 bronze badges 1
  • 1 AKA "ungroup a grouped list" – mkst Commented Feb 13 at 15:45
Add a comment  | 

5 Answers 5

Reset to default 4

One more fast, short solution:

q)where[count each d]iasc raze d
`a`b`c`a`b
q)d:`a`b`c!((0;3); (1;4); enlist 2)
q){exec k from `v xasc ungroup ([] k:key x;v:value x)} d
`a`b`c`a`b

Not sure about elegant but this should work

d:`a`b`c!((0;3); (1;4); enlist 2)
(raze (value count each d)#'key[d]),'raze d
`a 0
`a 3
`b 1
`b 4
`c 2

As for elegant, this is pretty elegant

raze key[d],''d
`a 0
`a 3
`b 1
`b 4
`c 2

I tried something different:

q)a:100000?`$string .Q.A
q)g:group a
q)\ts:1000 {{@[x;;:;]. y}/[(count raze v)#`;flip (v:value x;key x)]} g
1236 3181472
q)\ts:1000 {[d] where[count each d]iasc raze d } g
1357 3147184
q)\ts:1000 {exec k from `v xasc ungroup ([] k:key x;v:value x)} g
1662 5246496
q)\ts:1000 {[d](raze (value count each d)#'key[d]),'raze d} g
5817 9546512

If the domain is smaller, the speedup is more significant

q)a:100000?`$string 5#.Q.A
q)g:group a
q)\ts:1000 {{@[x;;:;]. y}/[(count raze v)#`;flip (v:value x;key x)]} g
489 3409648
q)\ts:1000 {[d] where[count each d]iasc raze d } g
962 3146432
q)\ts:1000 {exec k from `v xasc ungroup ([] k:key x;v:value x)} g
1145 5244832
q)\ts:1000 {[d](raze (value count each d)#'key[d]),'raze d} g
7138 9546512

Another way to skin the cat:

q){@[w;raze x;:;w:where count each x]}d
`a`b`c`a`b

Should perform pretty well over small and large domains.

This essentially becomes a "degroup" function - the opposite of group (which ungroup confusingly isn't)

本文标签: kdbTransform a kdb dictionary into a listStack Overflow