簡體   English   中英

Python分解大列表並將其轉換為較小列表

[英]Python breaking and transposing a large list into smaller lists

我有很多清單:

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]

我嘗試通過將較小的列表附加到較大的列表s並將它們轉換為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。

將所有內容都視為2d數組有效:

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]]

這是一個有點奇怪的解決方案:

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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM