1. 程式人生 > >python常用內置函數1

python常用內置函數1

ace type back 測試 style int 數值 字符串 most

1,abs 求絕對值

>>> abs( -1 )
1
>>> abs( 1 )
1
>>> 

2,max, min求序列最大值與最小值

>>> l = [ 1, 10, -6, 2, 100 ]
>>> max( l )
100
>>> min( l )
-6

3,len求列表的長度

>>> s = ghostwu
>>> len( s )
7
>>> l = [ 10, 20, 30 ]
>>> len( l )
3 >>> t = ( 10, 20 ) >>> len( t ) 2 >>> dic = { a : 10, b : 20, c : -1, d : 100 } >>> len( dic ) 4

4,divmod求商和余數

>>> divmod( 1, 2 )
(0, 1)
>>> divmod( 2, 1 )
(2, 0)
>>> 

5,pow,兩個值,冪運算,3個值,先冪運算,再除以第三個值,求余數

>>> pow( 3, 4 )
81 >>> pow( 2, 2, 6 ) 4 >>>

6,callable測試函數是否可以被調用

>>> callable( min )
True
>>> callable( f )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name f is not defined
>>> callable( abs )
True
>>> def f(): ... pass ... >>> callable( f ) True

7,類型判斷

>>> l = [ 10, 20 ]
>>> type( l )
<type list>
>>> type( [] )
<type list>
>>> if( type( [] ) == type( l ) ):
...     print yes
... 
yes
>>> t = ( 10, 20 )
>>> if( type( [] ) == type ( t ) ):
...     print yes
... else:
...     print no
... 
no
>>> 

也可以用isinstance判斷

>>> l = [ 10, 20 ]
>>> isinstance( l, list )
True
>>> type( () )
<type tuple>
>>> isinstance( ( 10, 20 ), tuple )
True
>>> isinstance( l, tuple )
False
>>> 

8,cmp比較字符串大小

>>> cmp( a, b )
-1
>>> cmp( b, ac )
1
>>> cmp( a, ab )
-1
>>> cmp( a, a )
0
>>> 

9,range與類型轉換等

>>> range( 1, 10 )
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range( -1, -10, -1 )
[-1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range( 1, 10, 5 )
[1, 6]
>>> 
>>> s = ghostwu
>>> type( s )
<type str>
>>> int( s )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ghostwu
>>> s = 20
>>> type( s )
<type str>
>>> int( s )
20
>>> type( s )
<type str>
>>> s + abc
20abc
>>> int( s ) + abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: int and str
>>> int( s ) + 10
30
>>> 

字符串為數值類型的才能轉成整形

當然還有其他類型轉換等

python常用內置函數1