一些基礎函式的筆記
阿新 • • 發佈:2018-12-29
1.round() 按指定的位數對數值進行四捨五入
>> round(3.1415926,2) #小數點後兩位 3.14 >>> round(3.1415926)#預設為0 3 >>> round(3.1415926,-2) 0.0 >>> round(3.1415926,-1) 0.0 >>> round(314.15926,-1) 310.0 >>>print "round(80.23456, 2) : ", round(80.23456, 2) round(80.23456, 2) : 80.23 >>>print "round(100.000056, 3) : ", round(100.000056, 3) round(100.000056, 3) : 100.0 >>>print "round(-100.000056, 3) : ", round(-100.000056, 3) round(-100.000056, 3) : -100.0 >>> [str(round(355/113, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']
2.set()是一個無序不重複元素集,不記錄元素位置或者插入點, 基本功能包括關係測試和消除重複元素. 集合內元素支援交併差等數學運算.
>>> x = set('spam') >>> y = set(['h','a','m']) >>> x, y (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) >>> x & y # 交集 set(['a', 'm']) >>> x | y # 並集 set(['a', 'p', 's', 'h', 'm']) >>> x - y # 差集 set(['p', 's'])
去除海量列表裡重複元素,用hash來解決也行,不過在效能上不是很高,用set解決只需幾行程式碼
>>> a = [11,22,33,44,11,22]
>>> b = set(a)
>>> b
set([33, 11, 44, 22])
>>> c = [i for i in b]
>>> c
[33, 11, 44, 22]
3.巢狀列表
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
4. strip() 方法用於移除字串頭尾指定的字元(預設為空格)。
>>>str = "0000000this is string example....wow!!!0000000";
>>>print str.strip( '0' );
this is string example....wow!!!'
>>> a = ' 123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'
5.rjust() , 它可以將字串靠右, 並在左邊填充空格
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of 'end' on previous line 注意前一行 'end' 的使用
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
另一個方法 zfill(), 它會在數字的左邊填充 0,
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
6.str.format()
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
括號及其裡面的字元 (稱作格式化欄位) 將會被 format() 中的引數替換。
在括號中的數字用於指向傳入物件在 format() 中的位置,如下所示:
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
如果在 format() 中使用了關鍵字引數, 那麼它們的值會指向使用該名字的引數。
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
7.range() ,生成數列
>>>range(1,5)#代表從1到5(不包含5)
[1,2,3,4]
>>>range(1,5,2)#代表從1到5,間隔2(不包含5)
[1,3]
>>>range(5)#代表從0到5(不包含5)
[0,1,2,3,4]