0. 新与旧
两种reverse
>>> L = [1,2,3,4] >>> R = L[::-1] # new object >>> R [4, 3, 2, 1] >>> L.reverse() # in place >>> L [4, 3, 2, 1] >>>
两种sort
>>> sorted(r) # new object [’black’, ’blue’, ’green’, ’red’, ’white’] >>> r [’white’, ’black’, ’green’, ’blue’, ’red’] >>> r. sort() # in-place >>> r [’black’, ’blue’, ’green’, ’red’, ’white’]
1. 函数参数
def f(a, b, c=0, *argc, **kw): print a, b, c, argc, kw
>>> f(1, 2, 3, ‘a‘, ‘b‘, ‘c‘, key=‘value‘)
1 2 3 (‘a‘, ‘b‘, ‘c‘) {‘key‘: ‘value‘}
a, b为必选参数,c默认参数,argc可变参数,kw为关键字参数。传入函数时,argc是一个tuple,kw为dict。
注意默认参数,一定要指向不可变变量。否者多个函数的同一参数可能指向同一个instance
>>> def foo(bar=[]): ... bar.append("baz") ... return bar >>> foo() ["baz"] >>> foo() ["baz", "baz"] >>> foo() ["baz", "baz", "baz"] >>> def foo(bar=None): ... if bar is None: # or if not bar: ... bar = [] ... bar.append("baz") ... return bar ... >>> foo() ["baz"] >>> foo() ["baz"] >>> foo() ["baz"]
2. 迭代
- 判断是否可迭代,使用Iterable
>>> from collections import Iterable >>> isinstance(‘string‘, Iterable) True >>> isinstance([1,2,3], Iterable) True >>> isinstance(123, Iterable) False
- 引入下标,可用enumerate
>>> for i, v in enumerate([‘a‘, ‘b‘, ‘c‘]): ... print i, v ... 0 a 1 b 2 c >>>
- 同时迭代多个list,使用函数zip
>>> for i, j in zip([1,2,3], [‘a‘, ‘b‘, ‘c‘]): ... print i, j ... 1 a 2 b 3 c
3. List Comprehension中的if-else
>>> L = [‘We‘, ‘are‘, 42, ‘ALONE‘, ‘!‘] >>> [s.lower() if isinstance(s,str) else s for s in L] [‘we‘, ‘are‘, 42, ‘alone‘, ‘!‘]
4. class
http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
限定class的成员
__slots__
>>> class Student(object): ... __slots__ = (‘name‘, ‘age‘) ...
5. exception
检查多个异常,需要放在tuple内
>>> try: ... l = ["a", "b"] ... int(l[2]) ... except (ValueError, IndexError) as e: ... pass ... >>>
时间: 2024-10-12 02:50:34