由于是边用边学,python的基本功不是太扎实,今天在对到python list comprehention的时候,想知道list comprehention里面
for 语句的执行顺序是什么,一查官方文档,发现时俺出现在list中的顺序执行,自己动手测试:
-
# about list iteratation
-
print [ i*j for i in xrange(5) for j in xrange(6,10,1) if i% 2 == 0]
-
# equal below
-
for i in xrange(5):
-
for j in xrange(6,10,1):
-
if i %2 == 0:
-
print i*j,
虽然list comprehention的功能很是强大,但是也不能无限制的使用,使用不好会使程序的可读性变差,只看一眼,你能看出这条语句的作用么?
点击(
此处)折叠或打开
-
print '\n'.join([ '\t'.join([ '%2dx%2d=%2d' % (j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)])
该语句的作用是打印小九九程序,但是理解起来,却还是比较晦涩的:怎么理解的?看定义:
A list comprehension consists of brackets containing an expression followed by a clause。
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
list_comprehension ::= "in" []
只不过,这里的expression比较复杂点,它本身也是list comprehention,即nest list comprehention,同时需要注意的是:
If the expression is a tuple (e.g. the (x, y) ), it must be parenthesized
即我们格式化的部分:
(j,i,i*j)
-
print '\n'.join([ '\t'.join([ '%2dx%2d=%2d' % (j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)])
-
[ '\t'.join([ '%2dx%2d=%2d' % (j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]
-
'\t'.join([ '%2dx%2d=%2d' % (j,i,i*j) for j in range(1,i+1)])
-
[ '%2dx%2d=%2d' % (j,i,i*j) for j in range(1,i+1)]
-
'%2dx%2d=%2d' % (j,i,i*j)
作为一个有其它编程语言的人,如果认为list comprehention 很简单,是不是在遇到这样的语法时,就有点蒙了,哈哈,因此官方文档的作用
举足轻重了,呵呵
明天如果有空读读函数参数定义需要注意到地方以及变量的unpack,pack。晚安!
ref:
http://www.python.org/dev/peps/pep-0202/
下面给出函数作用域的例子,比较简单,不在解释,注意一下vars 函数即可
-
# define one function
-
def localfun(para):
-
lscope=vars()
-
print lscope['para']
-
para='this is global scope'
-
gscope=vars()
-
print gscope['para']
-
localfun('this is lcoal scope')
help文档信息如下;
help> vars
Help on built-in function vars in module __builtin__:
vars(...)
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
阅读(2042) | 评论(0) | 转发(0) |