对嵌套列表的每个元素应用操作

时间:2018-05-26 11:15:00

标签: kdb

我有一个复杂的嵌套列表(深度也可以是> 2):

p:((`g;`d1`d2);(`r;enlist `e1);(`r;enlist `p1))

如何向嵌套列表的每个元素添加元素但保留原始结构;例如将`h添加到p的每个元素以获取以下内容:

((`g`h;(`d1`h;`d2`h));(`r`h;enlist `e1`h);(`r`h;enlist `p1`h))

我尝试了这个,但没有给出我想要的东西:

q)p,\:`h
((`g;`d1`d2;`h);(`r;enlist `e1;`h);(`r;enlist `p1;`h))

q)raze[p],\:`h
(`g`h;`d1`d2`h;`r`h;`e1`h;`r`h;`p1`h)

3 个答案:

答案 0 :(得分:4)

您可以使用.z.s递归浏览嵌套列表,只将function FakeElement () { this.events = Object.create(null); } FakeElement.prototype.addEventListener = function(eventName, handler) { var eventEntry = this.events[eventName]; if (!eventEntry) { eventEntry = this.events[eventName] = { handlers: [] }; } eventEntry.handlers.push(handler); }; FakeElement.prototype.trigger = function(eventName) { var event = {type: eventName}; // "Browser" creates the event var eventEntry = this.events[eventName]; var handlers = eventEntry && eventEntry.handlers; if (handlers) { handlers.forEach(function(handler) { handler.call(this, event); // "Browser" calls handler, passing }); // the event into it } }; // Using it: function zaehle(event) { console.log("zaehle got event: " + event.type); } var e = new FakeElement(); e.addEventListener("mouseover", zaehle); console.log("added handler for mouseover to element"); // Simulate the event occurring var timer = setInterval(function() { e.trigger("mouseover"); }, 500); setTimeout(function() { clearInterval(timer); }, 3000);附加到符号列表中:

`h

对于这个函数,我假设你的嵌套列表只包含符号。它检查列表的类型,如果它不是混合列表,则它会将q){$[0=type x;.z.s'[x];x,\:`h]}p g h d1 h d2 h `r`h ,`e1`h `r`h ,`p1`h 附加到每个元素。如果它是一个混合列表,那么它会将该列表的每个元素分别返回到函数中以再次检查。

答案 1 :(得分:2)

虽然不是递归的(因此需要一些关于嵌套列表形状的知识),但更常规的方法是

q).[p;2#(::);,';`h]
g    h    d1 h d2 h
`r`h      ,`e1`h
`r`h      ,`p1`h

答案 2 :(得分:1)

虽然托马斯已经回答了这个问题;如果您要指定append以外的任何其他操作,可以使用以下内容:

q)f:{`$ "_" sv string x,y}

q){[o;a;e] $[-11<>type e; .z.s [o;a] each e; o[e;a]] }[f;`h] each p
`g_h `d1_h`d2_h
`r_h ,`e1_h
`r_h ,`p1_h

或将f指定为append操作

q)f:{x,y}
q){[o;a;e] $[-11<>type e; .z.s [o;a] each e; o[e;a]] }[f;`h] each p
g    h    d1 h d2 h
`r`h      ,`e1`h
`r`h      ,`p1`h