如何在Qore中将长列表拆分成碎片

Pav*_*ton 5 arrays qore

我想在Qore中拆分列表,如下所示:

list a = (1,2,3,4,5,6);
list pieces = split_list_into_pieces(a, 2);
printf("%y\n", pieces);
Run Code Online (Sandbox Code Playgroud)

期望的输出:

[[1,2], [3,4], [5,6]]
Run Code Online (Sandbox Code Playgroud)

即我想要一个(据称很长)列表并将其分成给定(最大)长度的片段.

我可以这样做:

list sub split_list_into_pieces(list a, int length)
{
    int i = 0;
    list ret = ();
    list temp = ();
    foreach any x in (a)
    {
        temp += x;
        i++;
        if (i == length)
        {
            push ret, temp;
            temp = ();
            i = 0;
        }
    }
    if (temp)
    {
        push ret, temp;
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

但它不是很优雅,是吗?

更好的解决方案?

Mar*_*mek 7

你可以这样做:

list sub list_chunk(list a, int length) {
    list result = ();
    while (a)
        push (result, extract (a, 0, length));
    return result;
}
Run Code Online (Sandbox Code Playgroud)