list comprehensions列表解析

时间:2014-10-17 21:51:45   收藏:0   阅读:323

没有使用列表解析:

1 x =[]
2 for i in (1, 2, 3):
3     x.append(i)
4 
5 """
6 >>> x
7 [1, 2, 3]
8 """

 列表解析式:

1 x = [i for i in (1, 2, 3)]
2 """
3 >>> x
4 [1, 2, 3]
5 """

多重列表解析:

 1 x = [word.capitalize()
 2      for line in ("hello world?", "world!", "or not")
 3      for word in line.split()#空格分割
 4      if not word.startswith("or")]
 5 
 6 """
 7 >>> x
 8 [‘Hello‘, ‘World?‘, ‘World!‘, ‘Not‘]
 9 
10 """

 

创建一个字典和集合的方法也是一样的:

1 >>> {x: x.upper() for x in [hello, world]}
2 {world: WORLD, hello: HELLO}
3 
4 >>> {x.upper() for x in [hello, world]}
5 set([WORLD, HELLO])
6 >>> 

 

原文:http://www.cnblogs.com/jypwn/p/4032084.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!