python 技巧收录

来源:互联网 发布:华为媒体算法工程师 编辑:程序博客网 时间:2024/05/19 05:40


【选择赋值语句】在python2.5以上版本可用

req_dct = request.GET.copy() if request.method=='GET' else request.GET.copy()

【段注释】

前后分别使用三个双引号前面的双引号需要和下一行代码对齐后面的双引号最好写在代码的后面    """    i = 10    i += 20"""

【列表循环同时使用索引和元素】

for i, ch in enumerate(arr):    print ch, '(%d)' % i

【列表解析】

sqdEvens = [x**2 for x in range(8) if not x % 2]



【继续 \ 】

python语句可以使用换行分隔

if (weather_is_hot == 1) and \          (shark_warnings == 0):    dosth()


【lambda排序】

List=[People(21,'male'),People(20,'famale'),People(34,'male'),People(19,'famale')]List.sort(lambda p1,p2:cmp(p1.age, p2.age))List.sort(lambda p1,p2:-cmp(p1.age, p2.age))

【切片】

arr = [1, 2, 3, 4, 5]# arr[::-1] = [5, 4, 3, 2, 1]# arr[::2] = [1, 3, 5]


【多个比较】

>>> 3 < 4 <7  # same as (3<4) and (4<7)True




原创粉丝点击