Python內置函數示例

abs()

返回數字絕對值

>>> abs(-100)
100
>>> abs(10)
10
>>>

all()

判斷給定的可迭代參數 iterable 中的所有元素是否都爲 TRUE,如果是返回 True,否則返回 False

>>> all([100,100,100])
True
>>> all([3,0,1,1])
False
>>> 

any()

判斷給定的可迭代參數 iterable 是否全部爲 False,則返回 False,如果有一個爲 True,則返回 True

>>> any([0,0,0,0])
False
>>> any([0,0,0,1])
True
>>> 

ascii()

調用對象的repr()方法,獲取該方法的返回值

>>> ascii('test')
"'test'"
>>> 

bin()

將十進制轉換爲二進制

>>> bin(100)
'0b1100100'
>>> 

oct()

將十進制轉換爲八進制

>>> oct(100)
'0o144'
>>> 

hex()

將十進制轉換爲十六進制

>>> hex(100)
'0x64'
>>> 

bool()

測試對象是True,還是False

>>> bool(1)
True
>>> bool(-1)
True
>>> bool()
False
>>> 

bytes()

將一個字符轉換爲字節類型

>>> s = "blxt"
>>> bytes(s,encoding='utf-8')
b'blxt'
>>> 

str()

將字符、數值類型轉換爲字符串類型

>>> str(123)
'123'
>>>

callable()

檢查一個對象是否是可調用的

False
>>> callable(str)
True
>>> callable(int)
True
>>> callable(0)
False
>>> 

chr()

查看十進制整數對應的ASCll字符

>>> chr(100)
'd'
>>> 

ord()

查看某個ascii對應的十進制


>>> ord('a')
97
>>> 

classmethod()

修飾符對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # 調用 foo 方法
 

輸出結果:

func2
1
foo

compile()

將字符串編譯成python能識別或者可以執行的代碼。也可以將文字讀成字符串再編譯

>>> blxt = "print('hello')"
>>> test = compile(blxt,'','exec')
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>> 

complex()

創建一個複數

>>> complex(13,18)
(13+18j)
>>> 

delattr()

刪除對象屬性

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
 
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
 
delattr(Coordinate, 'z')
 
print('--刪除 z 屬性後--')
print('x = ',point1.x)
print('y = ',point1.y)
 
# 觸發錯誤
print('z = ',point1.z)

輸出結果:

>>> 
x =  10
y =  -5
z =  0
--刪除 z 屬性後--
x =  10
y =  -5
Traceback (most recent call last):
  File "C:\Users\fdgh\Desktop\test.py", line 22, in <module>
    print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'
>>> 

dict()

創建數據字典

>>> dict()
{}
>>> dict(a=1,b=2)
{'a': 1, 'b': 2}
>>> 

dir()

函數不帶參數時,返回當前範圍內的變量、方法和定義的類型列表

>>> dir()
['Coordinate', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'point1', 'y']
>>> 

divmod()

分別取商和餘數

>>> divmod(11,2)
(5, 1)
>>> 

enumerate()

返回一個可以枚舉的對象,該對象的next()方法將返回一個元組

>>> blxt = ['a','b','c','d']
>>> list(enumerate(blxt))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> 

eval()

將字符串str當成有效表達式來求值並返回計算結果取出字符串中內容

>>> blxt = "5+1+2"
>>> eval(blxt)
8
>>> 

exec()

執行字符串或complie方法編譯過的字符串,沒有返回值

>>> blxt = "print('hello')"
>>> test = compile(blxt,'','exec')
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>> 

filter()

過濾器,構建一個序列

#過濾列表中所有奇數
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

輸出結果:

[ 1, 3, 5, 7, 9 ]

float()

將一個字符串或整數轉換爲浮點數

>>> float(3)
3.0
>>> float(10)
10.0
>>> 

format()

格式化輸出字符串

>>> "{0} {1} {3} {2}".format("a","b","c","d")
'a b d c'
>>> print("網站名:{name},地址:{url}".format(name="blxt",url="www.blxt.best"))
網站名:blxt,地址:www.blxt.best
>>>

frozenset()

創建一個不可修改的集合

>>> frozenset([2,4,6,6,7,7,8,9,0])
frozenset({0, 2, 4, 6, 7, 8, 9})
>>> 

getattr()

獲取對象屬性

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # 獲取屬性 bar 值
1
>>> getattr(a, 'bar2')       # 屬性 bar2 不存在,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # 屬性 bar2 不存在,但設置了默認值
3
>>>

globals()

返回一個描述當前全局變量的字典

>>> print(globals()) # globals 函數返回一個全局變量的字典,包括所有導入的變量。
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 'runoob', '__package__': None}

hasattr()

函數用於判斷對象是否包含對應的屬性

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hasattr(a,'bar')
True
>>> hasattr(a,'test')
False

hash()

返回對象的哈希值

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hash(a)
-2143982521
>>> 

help()

返回對象的幫助文檔

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> help(a)
Help on A in module __main__ object:

class A(builtins.object)
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  bar = 1

>>> 

id()

返回對象的內存地址

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> id(a)
56018040
>>> 

input()

獲取用戶輸入內容

>>> input()
... test
'test'
>>> 

int()

用於將一個字符串或數字轉換爲整型

>>> int('14',16)
20
>>> int('14',8)
12
>>> int('14',10)
14
>>>

isinstance()

來判斷一個對象是否是一個已知的類型,類似 type()

>>> test = 100
>>> isinstance(test,int)
True
>>> isinstance(test,str)
False
>>> 

issubclass()

用於判斷參數 class 是否是類型參數 classinfo 的子類


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A:
    pass
class B(A):
    pass
    
print(issubclass(B,A))    # 返回 True

iter()

返回一個可迭代對象,sentinel可省略

>>>lst = [1, 2, 3]
>>> for i in iter(lst):
...     print(i)
... 
1
2
3

len()

返回對象的長度

>>> dic = {'a':100,'b':200}
>>> len(dic)
2
>>> 

list()

返回可變序列類型

>>> a = (123,'xyz','zara','abc')
>>> list(a)
[123, 'xyz', 'zara', 'abc']
>>> 

map()

返回一個將function應用於iterable中每一項並輸出其結果的迭代器

>>>def square(x) :            # 計算平方數
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 計算列表各個元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函數
[1, 4, 9, 16, 25]
 
# 提供了兩個列表,對相同位置的列表數據進行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

max()

返回最大值

>>> max (1,2,3,4,5,6,7,8,9)
9
>>> 

min()

返回最小值

>>> min (1,2,3,4,5,6,7,8)
1
>>> 

memoryview()

返回給定參數的內存查看對象(memory view)

>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'
>>>

next()

返回可迭代對象的下一個元素

>>> a = iter([1,2,3,4,5])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4
>>> next(a)
5
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    next(a)
StopIteration
>>>

object()

返回一個沒有特徵的新對象

>>> a = object()
>>> type(a)
<class 'object'>
>>> 

open()

返回文件對象

>>>f = open('test.txt')
>>> f.read()
'123/123/123'

pow()

base爲底的exp次冪,如果mod給出,取餘

>>> pow (3,1,4)
3
>>> 

print()

打印對象

class property()

返回property屬性

class C(object):
    def __init__(self):
        self._x = None
 
    def getx(self):
        return self._x
 
    def setx(self, value):
        self._x = value
 
    def delx(self):
        del self._x
 
    x = property(getx, setx, delx, "I'm the 'x' property.")

range()

生成一個不可變序列

>>> range(10)
range(0, 10)
>>> 

reversed()

返回一個反向的iterator

>>> a = 'test'
>>> a
'test'
>>> print(list(reversed(a)))
['t', 's', 'e', 't']
>>> 

round()

四捨五入

>>> round (3.33333333,1)
3.3
>>> 

class set()

返回一個set對象,可實現去重

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> set(a)
{1, 2, 3, 4, 5, 6}
>>> 

class slice()

返回一個表示有1range所指定的索引集的slice對象

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> a[slice(0,3,1)]
[1, 2, 3]
>>> 

sorted()

對所有可迭代的對象進行排序操作

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sorted(a,reverse=True)
[6, 5, 5, 5, 4, 4, 3, 3, 2, 2, 1]
>>> 

@staticmethod

將方法轉換爲靜態方法

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class C(object):
    @staticmethod
    def f():
        print('blxt');
 
C.f();          # 靜態方法無需實例化
cobj = C()
cobj.f()        # 也可以實例化後調用

輸出結果:

	test
	test

sum()

求和

a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sum(a)
40
>>> 

super()

返回一個代理對象

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

tuple()

不可變的序列類型

>>> a = 'www'
>>> b =tuple(a)
>>> b
('w', 'w', 'w')
>>> 

zip()

將可迭代的對象作爲參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包爲元組的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素個數與最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 與 zip 相反,*zipped 可理解爲解壓,返回二維矩陣式
[(1, 2, 3), (4, 5, 6)]

點擊這裏跳轉個人博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章