Skip to content

Instantly share code, notes, and snippets.

@recuraki
Last active November 7, 2016 14:49
Show Gist options
  • Save recuraki/132d49767019b249d27a34a078c05076 to your computer and use it in GitHub Desktop.
Save recuraki/132d49767019b249d27a34a078c05076 to your computer and use it in GitHub Desktop.
l = [100,200,201,202,203,301,303,305,306,401,402,403,405,501,502,601,602,603,701]
#これを
# [[701, 603, 602, 601, 502, 501, 405, 403, 402], [401, 306, 305, 303, 301, 203, 202, 201, 200], [100]]
#こうしたい
from itertools import zip_longest
#########################################
# zipすると端数分が消されちゃう
# [[100, 200, 201, 202, 203, 301, 303, 305, 306], [401, 402, 403, 405, 501, 502, 601, 602, 603]]
# 違う!そうじゃない。そうだよね。長いのに揃っちゃうのがzipだ。
print([list(x) for x in zip(*[iter(l)]*9)])
#########################################
# zip_longestっていうのがあった
# [[100, 200, 201, 202, 203, 301, 303, 305, 306], [401, 402, 403, 405, 501, 502, 601, 602, 603], [701, None, None, None, None, None, None, None, None]]
# 惜しい!違う!そうじゃないんだ!Noneいらないから!
print([list(x) for x in zip_longest(*[iter(l)]*9)])
#########################################
# 一応できた
# [[100, 200, 201, 202, 203, 301, 303, 305, 306], [401, 402, 403, 405, 501, 502, 601, 602, 603], [701]]
print([list(filter(lambda a: a is not None, x)) for x in zip_longest(*[iter(l)]*9)])
#########################################
# こうかなー。
# [[100, 200, 201, 202, 203, 301, 303, 305, 306], [401, 402, 403, 405, 501, 502, 601, 602, 603], [701]]
def f(s, l = 9):
while s:
r,s = s[:9], s[9:]
yield r
print([x for x in f(l)])
#########################################
# 内包リスト表記は無理やりか
# [[100, 200, 201, 202, 203, 301, 303, 305, 306], [401, 402, 403, 405, 501, 502, 601, 602, 603], [701]]
def f(s,l = 9):
s = s.copy() # popするから破壊しないようにする
while s:
yield [s.pop(0) for i in range(len(s) if len(s) < l else l)]
print([x for x in f(l)])
#########################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment