Python 琐记一
1. BOOL
Python 中bool类型把数0看作falsebool(0)
2. range
最常用的函数range,可传递1、2或3个参数,只有1个则是下边界,两个就是上下边界,三个则加上了步长。
3. lambda
类似于函数式程序语言Lisp,Python提供了lambda
f = lambda x,y: x+y
print f(1,2)
但是lambda功能有限,它只是一个表达式,不是一个语句,lambda会返回一个值,而不需要return,事实上使用了return就会出现语法错误
lambda实际上就是def的简化形式,但是它可以在列表等数据容器中出现
4. map
map函数处理的是函数,它对一个List对象的每一项都调用了一个传递的函数,并返回一个包含所有调用结果的列表
l = [1,2,3,4,5,6,7]
def inc2times(x):
return x+x;
r = map(inc2times,l)
print r
print map(lambda x: x+x, l)
5. 函数式编程
python事实上完全支持函数式编程,函数即对象,这与JavaScript一致,函数可以作为对象来传递、调用,被作为列表的元素等
6. 嵌套函数的作用域
嵌套的函数对自己的局部作用域,包含自己模块的全局作用域以及内置的名字作用域有访问权,它对包含自己的函数的作用域无访问权。无论多深的函数嵌套都只能看见三个作用域。
def outer(x):
def inner(i):
print i
if(i):
innenr(i-1)
inner(x)
outer(3)
上述代码就会语法出错。
7. name
每一个模块都有一个内置属性__name__
如果文件作为程序运行,在启动时,name__设置为字符串__main
如果文件是被导入的,__name__设置为用户已知的模块名
8.site-packages和disk-packages的区别
dist-packages is a Debian-specific convention that is also present in its derivatives, like Ubuntu. Modules are installed to dist-packages when they come from the Debian package manager into this location: /usr/lib/python2.7/dist-packages Since easy_install and pip are installed from the package manager, they also use dist-packages, but they put packages here: /usr/local/lib/python2.7/dist-packages From the Debian Python Wiki: dist-packages instead of site-packages. Third party Python software installed from Debian packages goes into dist-packages, not site-packages. This is to reduce conflict between the system Python, and any from-source Python build you might install manually. This means that if you manually install Python from source, it uses the site-packages directory. This allows you to keep the two installations separate, especially since Debian and Ubuntu rely on the system version of Python for many system utilities.
9. 中文注释
在Linux中Python代码中加入中文注释提示编码错误,解决方案:
文件头加入# coding:utf-8
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment
GitalkLivere