python知识集锦

一. 过滤list

语法

[expresion for element in list if condition]     

例子:

li = ["a", "b", "c", "wahaha", "c"]

[elem for elem in li if li.count(elem) == 1]

又如:

>>> methodList = [method for method in dir(li) if callable(getattr(li, method))]

>>> methodList

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

2. 连接数据库编码问题

添加:

import sys

sys.path.append((os.path.join(os.path.dirname(__file__), "lib")))
reload(sys)
sys.setdefaultencoding('utf-8')

原理:

这个setdefaultencoding是在系统启动的时候就设置了,就是你在控制台下输入python出现>>> 的时候系统会自动的读取一个
文件,所以当你在使用中的python时就必须重新reload,如果不想用那一句的话,可以在/usr/lib/python2.4/ 下建立一个名为 sitecustomize.py 文件内容为:     
    import sys
    sys.setdefaultencoding('utf-8')
这样的话就可以不用每次去reload了,他会在每次启动python的时候自动读取这个文件!!

猜你喜欢

转载自michaelzqm.iteye.com/blog/1756421
今日推荐