In [10]: test = [1,2,"yes"]python
---append(x) 追加到鏈尾app
In [11]: test.append(1)函數
In [12]: test Out[12]: [1, 2, 'yes', 1]ip
---extend(L) 追加一個列表,等價於+=rem
In [14]: test.extend(['no','maybe'])input
In [15]: test Out[15]: [1, 2, 'yes', 1, 'no', 'maybe']io
---insert(i,x) 在位置i插入x,其他元素向後推。若是i大於列表的長度,就咋最後添加。若是i小於0,就在最開始處添加。ast
In [16]: test.insert(0,'never')test
In [17]: test Out[17]: ['never', 1, 2, 'yes', 1, 'no', 'maybe']module
---remove(x) 刪除第一個值爲x的元素,若是不存在就會拋出異常
In [18]: test.remove('no')
In [19]: test Out[19]: ['never', 1, 2, 'yes', 1, 'maybe']
列表推導式
語法:[<expr1> for k in L if <expr2>]
表示在列表L中,若是expr2爲真,就循環執行expr1語句併產生一個列表。
In [23]: vec = [2,4,6]
In [25]: [3*x for x in vec if x>3]
Out[25]: [12, 18]
---函數傳參數解析
In [18]: def test(x,y=1,*a,**b): ....: print x,y,a,b ....:
In [19]: test(1)
1 1 () {}
In [20]: test(1,2)
1 2 () {}
In [21]: test(1,2,3,4)
1 2 (3, 4) {}
In [22]: test(1,a=2)
1 1 () {'a': 2}
In [23]: test(1,2,3,a=4)
1 2 (3,) {'a': 4}
In [24]: test(1,2,3,y=4)
--------------------------------------------------------------------------- TypeError
Traceback (most recent call last) <ipython-input-24-3cd70699dda1> in <module>() ----> 1 test(1,2,3,y=4)
TypeError: test() got multiple values for keyword argument 'y'
*傳遞的是元組(tuple)
**傳遞的是字典(dictionary)
map()---至少須要兩個參數,第一個是一個函式,第二個是傳入函式的參數
map()中的第一個參數爲None,則返回原來的序列;若是傳入多個序列,則會將其中每一個位置的參數打包成tuple。
In [37]: def foo(x,y): ....: return x**y ....:
In [38]: print map(foo,range(10),range(10))
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]
In [39]: print map(None,range(10),range(10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
---實現100之內的偶數
In [40]: def foo_filter(x):
....: return x%2==0
In [42]: print filter(foo_filter,range(100))[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]