天天看点

Python基础教程---读书笔记五

1. 从模块导入函数的方法,也可以为函数提供别名:

   import somemodule; from somemodule import somefunction1, somefunction2; from somemodule import *; from somemodule import somefunction as newfunctionname;

2. 序列解包支持多个赋值同时进行:

   >>> x,y,z=1,2,3

   >>> print x,y,z

   1 2 3

   >>> values=(3,2,1)

   >>> x,y,z=values

   3 2 1

3. 链式赋值:将同一个值赋给多个变量,注意同一性问题;x=y=somefuntion();

4. 增量赋值:x+=1; x*=2; str+='abc'; str*=2;

5. 布尔变量:False,None,0,"",(),[],{}都被看做假;其他都被看做真;bool()函数将其他值转换为布尔值;

6. 比较运算符:支持链式比较,如0<age<100;比较运算都支持字符串,按字母顺序排列;

   x==y; x<y; x>y; x>=y; x<=y; x!=y;

   x is y; x is not y; #判断x,y是不是同一对象;

   x in y; x not in y; #判断x是不是y的成员;

7. 布尔运算符:and; or; not

8. Python中的断言使用关键字assert: assert 0<age<100

9. 循环while/for;遍历一个集合时,用for:

   >>> values=[3,2,1]

   >>> for value in values: print value

   ...

   3

   2

   1

   >>> for value in range(1,3): print value

10. 遍历字典元素:

   >>> d={'x':1, 'y':2, 'z':3}

   >>> for key in d: print key, 'corresponse to', d[key]

   y corresponse to 2

   x corresponse to 1

   z corresponse to 3

   >>> for key,value in d.items(): print key, 'corresponse to', value

11. 一些有用的迭代函数:

   并行迭代:同时迭代两个序列

       >>> names=['ab','cd', 'ef']

       >>> ages=[12,34,56]

       >>> for i in range(len(names)): print names[i], 'is', ages[i], 'years old'

       ...

       ab is 12 years old

       cd is 34 years old

       ef is 56 years old

       >>> zip(names, ages)

       [('ab', 12), ('cd', 34), ('ef', 56)]

       >>> for name, age in zip(names, ages): print name, 'is', age, 'years old'

   编号迭代:取得迭代序列中对象的同时,获取当前对象的索引

       for index, string in enumerate(strings):

           if 'xxx' in string:

               strings[index]='[censorted]'

   翻转和排序迭代:reversed()函数和sorted()函数,注意不是原地操作

       >>> sorted([25, 3, 4, 8])

       [3, 4, 8, 25]

       >>> ''.join(reversed('Hello, world!'))

       '!dlrow ,olleH'

12. 循环中的else子句:

   from math import sqrt

   for n in range(99, 81, -1):

       root=sqrt(n)

       if root == int(root):

           print n

           break

   else:

       print "Didn't find it!"

13. 列表推导式

   >>> [(x,y) for x in range(3) for y in range(3) if x+y>=3]

   [(1, 2), (2, 1), (2, 2)]

14. pass语句什么都不做,作为占位符使用;del语句用来删除变量或者数据结构中的一部分,不能删除值;exec语句执行字符串中的语句,可以使用命名空间;eval语句对字符串中的表达式进行计算并返回结果;

本文转自jazka 51CTO博客,原文链接:http://blog.51cto.com/jazka/1344366,如需转载请自行联系原作者