Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created August 6, 2012 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasberth/3273859 to your computer and use it in GitHub Desktop.
Save pasberth/3273859 to your computer and use it in GitHub Desktop.
python の itertools で遊ぶ
import itertools
# このへん参考: http://kk6.hateblo.jp/entry/20110521/1305984781
# zip_longest はもっとも長いイテレータに合わせて繰り返す
# 終わったイテレータには None が入る
# [('a', 1), ('b', 2), ('c', None), ('d', None), ('e', None), ('f', None)]
print([(char, n) for char, n in itertools.zip_longest("abcdef", range(1, 3))])
# [(1, 'a'), (2, 'b'), (None, 'c'), (None, 'd'), (None, 'e'), (None, 'f')]
print([(char, n) for char, n in itertools.zip_longest(range(1, 3), "abcdef")])
# python -V # => Python 3.2.3
# zip 関数はなかった。
# 3.2.3 では itertools.zip() はなかったけど組み込みのzipでよい
if not 'zip' in dir(itertools) or 'izip' in dir(itertools):
print("itertools.zip() not found.")
# もちろんイテレータを組み合わせたりできる
# リストではなくジェネレータを返すので速度とかの心配は特にない(と思う)
# a 1
# b 2
# c 1
# d 2
# e 1
# f 2
# この例だと zip_longest() では "abcdef" が終了してもループが終わらず無限に繰り返してしまう
for x, y in zip("abcdef", itertools.cycle(range(1,3))):
print(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment