分类: Python/Ruby
2009-04-14 16:26:27
L = [1,2,3,4,5,6,7,8,9] zip(*(iter(L),)*3)
python reference中的解释:
zip([iterable,...])
returns a list of tuple, where the i-th element from each argument sequences or iterables.The returned list is truncated in length to the length of the shortest argument sequence. 返回一个tuple的列表。比如:>>> x = [1,2,3]
>>> y = [4,5,6]
>>> zipped = zip(x,y)
>>> zipped
[(1,4),(2,5),(3,6)] 实际上,zip做的事情便是依次调用可遍历对象的next()函数,遍历一次,组成一个tuple。 比如 zip(x,y) 实际上相当于调用x = iter(x), y = iter(y), 之后, [(x.next(),y.next()),(x.next(),y.next()),(x.next(),y.next()),...]。直到 x.next() or y.next() 抛出 StopIteration 的异常。
>>> x = [1,2,3] >>> y = [4,5,6] >>> x = iter(x) >>> x.next() 1 >>> x.next() 2 >>> x.next() 3 >>> x.next() Traceback (most recent call last): File "" , line 1, inStopIteration
zip(*L)用来对一个zip后的数组做unzip操作。
>>> x2,y2 = zip(*unzipped) >>> x2 == x, y2 == y True
>>> L = [1,2,3] >>> li = (L,)*3 >>> li ([1, 2, 3], [1, 2, 3], [1, 2, 3]) >>> li[0][1] = 9 >>> li ([1, 9, 3], [1, 9, 3], [1, 9, 3])
>>> L = [1,2,3,4,5,6,7,8,9] >>> a = zip(*(iter(L),)*3) >>> >>> (iter(L),)*3 >>> (object at 0xb7deae6c>, object at 0xb7deae6c>, object at 0xb7deae6c>) >>> a [(1, 2, 3), (4, 5, 6), (7, 8, 9)]