Created
July 21, 2011 23:58
-
-
Save oyakata/1098536 to your computer and use it in GitHub Desktop.
ジェネレータ式を使ったサンプルをいくつかメモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding:utf-8 -*- | |
# 総当りジェネレータ | |
round_robin = lambda L: ((i, j) for i in L for j in L if not i is j) | |
# タプル -> 辞書リスト | |
tpl2dcts = lambda L: (dict(zip(L[0], x)) for x in L[1:]) | |
# 2要素ずつ取り出したタプルのジェネレータ | |
pairs = lambda L: ((L[x], L[x+1]) for x in xrange(0, len(L), 2)) | |
import unittest | |
class GeneratorTest(unittest.TestCase): | |
def test_round_robin(self): | |
L = list(round_robin([1, 2, 3, 4])) | |
self.assertEqual(L, [ | |
(1, 2), (1, 3), (1, 4), | |
(2, 1), (2, 3), (2, 4), | |
(3, 1), (3, 2), (3, 4), | |
(4, 1), (4, 2), (4, 3), | |
]) | |
def test_tpl2dcts(self): | |
datas = ( | |
("foo", "bar", "baz"), | |
(1, 2, 3), | |
(4, 5, 6), | |
(7, 8, 9), | |
) | |
L = list(tpl2dcts(datas)) | |
self.assertEqual(L, [ | |
dict(foo=1, bar=2, baz=3), | |
dict(foo=4, bar=5, baz=6), | |
dict(foo=7, bar=8, baz=9), | |
]) | |
def test_pairs(self): | |
L = list(pairs("trebor sux")) | |
self.assertEqual(L, [ | |
("t", "r"), ("e", "b"), ("o", "r"), (" ", "s"), ("u", "x"), | |
]) | |
if __name__ == "__main__": | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment