0

我有一个很大的清单:

X= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

我想转换成更小的列表:(x1-x5 是用于重新映射 X 中的数据的占位符,对于 X=17,更小的列表的长度才是最重要的)

x1 = [0, 1], 
x2 = [0, 1, 2, 3] 
x3 = [0, 1, 2, 3] 
x4 = [0, 1, 2, 3]
x5 = [0, 1]

预期结果:将大列表中的数据映射到 x1-x5,如下所示:

x1 = [0, 5]
x2 = [1, 6, 10, 13] 
x3 = [2, 7, 11, 14] 
x4 = [3, 8, 12, 15]
x5 = [4, 9]

我尝试通过将较小的列表附加到一个大列表中并将它们转换为 t 来向后工作,如下所示:

s = [[0, 1], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1]]
t=map(None,*s) 
[(0, 0, 0, 0, 0), (1, 1, 1, 1, 1), (None, 2, 2, 2, None), (None, 3, 3, 3, None)]

这就是我卡住的地方。这里的任何帮助将不胜感激。我确信有一种更简单的方法可以做到这一点,而无需附加并将 x 重新映射为 t,并将 t 分解为 x1 -x5。

4

2 回答 2

1

将所有内容视为二维数组有效:

def transpose_into(x, splits):
    max_col = max(splits)
    res = [[None] * split for split in splits]
    col = 0
    xiter = iter(x)
    while True:
        for sub_list in res:
            try:
                sub_list[col]
                sub_list[col] = next(xiter)
            except IndexError:
                continue
        col += 1
        if col > max_col:
            break
    return res
assert transpose_into(x, splits) == [[0, 5], [1, 6, 10, 13], [2, 7, 11, 14], 
                                     [3, 8, 12, 15], [4, 9]]
于 2013-06-02T19:29:01.367 回答
0

这是一个有点奇怪的解决方案:

import itertools

def transpose_into(data, sizes):
    parts = [([], size) for size in sizes]

    # build a cycling iterator over the resultant lists
    iterparts = itertools.cycle(parts)

    for value in data:
        # Iterate at most once through the cycle
        for group, size in itertools.islice(iterparts, len(parts)):
            # put our value in the list if it's not full
            if len(group) < size:
                group.append(value)
                break
        else:
            # completed cycle, all lists full - stop
            break

    return [group for group, size in parts]
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
>>> splits = [2, 4, 4, 4, 2]
>>> transpose_into(x, splits)
[[0, 5], [1, 6, 10, 13], [2, 7, 11, 14], [3, 8, 12, 15], [4, 9]]
于 2013-06-02T18:17:54.163 回答