2010年8月20日星期五

优雅

用 map 来转置矩阵
>>> a = map(None, range(10), range(10, 20), range(20, 30))
>>> a
[(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24), (5, 15, 25), (6, 16, 26), (7, 17, 27), (8, 18, 28), (9, 19, 29)]
>>> b = map(None, *a)
>>> b
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19), (20, 21, 22, 23, 24, 25, 26, 27, 28, 29)]
>>> map(None, *b)
[(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24), (5, 15, 25), (6, 16, 26), (7, 17, 27), (8, 18, 28), (9, 19, 29)]
>>> a == map(None, *b)
1
======
以前看过有关的讨论,不过当时是因为不太明白 * 是干嘛的,看过就算。今天算是搞明白了。太优雅了~萌死了……
======
update: 20100822
>>> a = (1, 2 ,3), (1, 2, 3, 4), (1, 2, 3, 4, 5)
>>> zip(*a)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
>>> map(None, *a)
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (None, 4, 4), (None, None, 5)]
原来 zip 也可以做这个,和 map 的不同之处在于 zip 以最短的为准,长出来的丢掉, map 则是以最长的为准,不够的用 None 补上。真是可爱啊~

没有评论:

发表评论