我有一个很大的清单:
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。
答案 0 :(得分:1)
将所有内容视为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]]
答案 1 :(得分: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]]