Chinaunix首页 | 论坛 | 博客
  • 博客访问: 249721
  • 博文数量: 91
  • 博客积分: 4185
  • 博客等级: 上校
  • 技术积分: 855
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-29 16:18
文章分类

全部博文(91)

文章存档

2014年(3)

2013年(1)

2012年(8)

2011年(2)

2010年(5)

2009年(68)

2008年(4)

我的朋友

分类: Python/Ruby

2009-04-14 16:26:27

What does this do?
L = [1,2,3,4,5,6,7,8,9]
zip(*(iter(L),)*3)

Firstly

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, in 
StopIteration

zip(*L)用来对一个zip后的数组做unzip操作。

>>> x2,y2 = zip(*unzipped)
>>> x2 == x, y2 == y
True

secondly

>>> 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])

Thirdly

>>> 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)]
阅读(652) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~