最全Python內置函數


內置函數的基本使用

abs的使用:

取絕對值

1 abs
print(abs(123))
print(abs(-123))

result:
123
123

all的使用:

循環參數,如果每個元素都為真的情況下,那么all的返回值為True:

假: 0, None, "", [],(), {}

ret = all([True, True])

ret1 = all([True, False])

result:

True

False

any的使用:

只要有一個為True,則全部為True

ret = any(None, "", [])

ret1 = any(None, "", 1)

result:

False

True

ascii的使用:

回去對象的類中,找到__repr__方法,找到該方法之后獲取返回值

class Foo:

    def __repr__(self):

        return "hello"

obj = Foo()

ret = ascii(obj )

自動去對象(類)中找到  __repr__方法獲取其返回值

bin的使用:

二進制

ret = bin(11)

result:

0b1011

oct的使用:

八進制

ret = oct(14)

result:

0o16

int的使用:

十進制

ret = int(10)

result:

10

hex的使用:

十六進制

ret = hex(14)

result:

0xe          0x:表示16進制   e: 表示14

bool的使用:

判斷真假,  True:真  ,  False:假,   把一個對象轉換成bool值

ret = bool(None)

ret = bool(1)

result:

False

True

bytearray的使用:

字節列表

列表元素是字節,

bytes的使用:

字節

bytes("xxx", encoding="utf-8")

callable的使用:

判斷對象是否可被調用

class Foo:            #定義類
    pass

foo = Foo()          # 生成Foo類實例
print(callable(foo))   #  調用實例
ret = callable(Foo)    # 判斷Foo類是否可被調用
print(ret)

result:
False
True                            

chr的使用:

給數字找到對應的字符

ret = chr(65)

result:

A

ord的使用:

給字符找到對應的數字

ret = ord("a")

result:

a

classmethod的使用:

修飾符

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

class A(object):
    bar = 1
    def func(self):
        print("func")
    @classmethod
    def func2(cls):
        print("func2")
        print(cls.bar)
        cls().func()    # 調用func方法

A.func2()     # 不需要實例化


result:
func2
1
func

compile的使用:

函數講一個字符串編譯為字節代碼

compile(source, filename, mode[, flags[, dont_inherit]])


參數:
source      字符串或者AST(Abstract Syntax Trees對象)

filename    代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值

mode         指定編譯代碼的種類,可指定: exec, eval, single

flags          變量作用域,局部命名空間,如果被提供,可以是任何映射對象。

flags和dont_inherit是用來控制編譯源碼時的標志
str_for = "for i in range(1,10): print(i)"
c = compile(str_for, '', 'exec')            # 編譯為字節代碼對象
print(c)
print(exec(c))

result:
1
2
3
4
5
6
7
8
9

complex的使用:

函數用於創建一個值為 real + image * j 的復數或者轉化一個字符串或數為復數,如果第一個參數為字符串,則不需要指定第二個參數。

語法:

class complex([real ,[ image]])

參數說明:
real        int, long, float或字符串

image     int,long,float
ret1 = complex(1,2)
print(ret1)

ret2 = complex(1)
print(ret2)

ret3 = complex("1")
print(ret3)

ret4 = complex("1+2j")
print(ret4)

result:返回一個復數
(1+2j)
(1+0j)
(1+0j)
(1+2j)

delattr的使用:

用於刪除屬性

delattr(x, "foobar")   相等於  del x.foobar

語法:

delattr(object, name)

參數:
object     對象

name      必須是當前對象的屬性
class DelClass:
    x = 10
    y = -5
    z = 0

obj = DelClass
print("x", obj.x)
print("y", obj.y)
print("z", obj.z)

delattr(DelClass, 'z')
print("x", obj.x)
print("y", obj.y)
print("報錯", obj.z)

result:

x 10
y -5
z 0
x 10
y -5
    print("報錯", obj.z)
AttributeError: type object 'DelClass' has no attribute 'z'

dict的使用:

字典的使用方法

new_dict = dict()
new_dict['key1'] = "test"
print(new_dict)

dir的使用:

該方法將最大限制地收集參數信息, 查看當前,變量,方法, 類型的屬性以及功能。

print(dir())
list_one = list()
print(dir(list_one))
 
result:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
 
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

divmod的使用:

將除數和余數運算結果結合起來,返回一個包含商和余數的元祖。

ret = divmod(7, 2)
print(ret)
ret_one = divmod(8, 2)
print(ret_one)

參數: 數字

result:
(3, 1)
(4, 0)

enumerate的使用:

 用於將一個可遍歷的數據對象(list, tuple,str)組合為一個索引序列,同時列出數據,和數據下標。

test_list = [1, 2, 3, 4, 5]
for data_index, data in enumerate(test_list):
    print("下標:{0},數據{1}".format(data_index, data))

參數:
sequence        一個序列,迭代器或其他支持迭代對象
start               下標起始位置

result:
下標:0,數據1
下標:1,數據2
下標:2,數據3
下標:3,數據4
下標:4,數據5

eval的使用:

 用來執行一個字符串表達式,並且返回表達式的值

x = 7
ret = eval('x + 3')
print(ret)

參數:
expression             表達式

globals                   變量作用域,全局命名空間

locals                     變量作用域,局部命名空間

result:
10

exec的使用:

 執行存儲在字符串或文件中的python語句,相比eval,exec可以執行更復雜的python代碼

import time
ret = exec("""for i in range(0,5): 
                    time.sleep(1)   
                    print(i) """)


# 注意代碼塊中的縮進

result:

0
1
2
3
4

filter的使用:

 用於過濾序列,過濾掉不符合條件的元素,返回符合條件元素組成的新list

def is_odd(n):
    return n % 2 == 1


newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

參數:
function      判斷函數

iterable       可迭代對象


result:
[1, 3, 5, 7, 9]

float的使用:

將整形轉換成小數形

a_int = 10
b_float = float(a_int)
print(a_int)
print(b_float)


result:
10
10.0

format的使用:

字符串序列化,可以序列多種類型

str_format = "Helle World"

list_format = ['list hello world']

dict_format = {"key_one":"value_one"}

ret_format_one = "{0}".format(str_format)
ret_format_two = "{0}".format(list_format)
ret_format_three = "{0}".format(dict_format)
print(ret_format_one)
print(ret_format_two)
print(ret_format_three)

result:
Helle World
['list hello world']
{'key_one': 'value_one'}

frozenset的使用:

 返回一個凍結集合,集合凍結之后不允許添加,刪除任何元素

a = frozenset(range(10))    # 生成一個新的不可變集合
print(a)

b = frozenset('wyc')           # 創建不可變集合
print(b)



result:
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
frozenset({'w', 'y', 'c'})

getattr的使用:

用於返回一個對象的屬性值

class Foo(object):
    bar = 1

obj = Foo()
print(getattr(obj, 'bar'))              # 獲取屬性bar的默認值

print(getattr(obj, 'bar2'))             # 不存在,沒設置默認值,則報錯

print(getattr(obj, 'bar2', 3))          # 屬性2不存在,則設置默認值即可

result:
1

 print(getattr(obj, 'bar2'))
AttributeError: 'Foo' object has no attribute 'bar2'

3        

globals的使用:

會以字典類型返回當前位置的全部全局變量

print(globals())

result:
{'__cached__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__package__': None, '__file__': 'C:/Users/Administrator/PycharmProjects/untitled/day1.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000011E78626B70>, '__spec__': None} 

hasattr的使用:

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

class Foo:
    x = 10
    y = 20
    z = 0

obj = Foo()
print(hasattr(obj, 'x'))
print(hasattr(obj, 'k'))

result:
True
False

hash的使用:

 用於獲取一個對象(字符串或者數值等)的哈希值

str_test = "wyc"
int_test = 5


print(hash(str_test))
print(hash(int_test))

result:
1305239878169122869
5

help的使用:

幫助查看類型有什么方法

str_test = "wyc"
print(help(str))



result:
結果有點小長,就不粘貼再此了 

id的使用:

查看當前類型的存儲在計算機內存中的id地址

str_test = "wyc"
print(id(str_test))

result:
2376957216616 

input的使用:

接受標准數據,返回一個string類型

user_input = input("請輸入:")
print(user_input)

result:
請輸入:wyc
wyc

isinstance的使用:

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

a = 1
print(isinstance(a, int))
print(isinstance(a, str))


result:
True
False

issubclass的使用:

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

class A:
    pass
class B(A):
    pass

print(issubclass(B, A))       # 判斷B是否是A的子類

result:
True

iter的使用:

 用來生成迭代器

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


result:
1
2
3

len的使用:

查看當前類型里邊有多少個元素

str_one = "hello world"
lst = [1, 2, 3]
print(len(str_one))          # 空格也會算一個元素
print(len(lst))    

result:
11
3

list的使用:

列表

list = [1, 2, 3, 4, 5]

方法:
索引:  index
切片: [1:3]
追加: append
刪除: pop
長度: len
擴展: extend
插入: insert
移除:remove
反轉: reverse
排序:sort

locals的使用:

 以字典類型返回當前位置的全部,局部變量

def func(arg):
    z = 1
    return locals()

ret = func(4)
print(ret)

result:
{'arg': 4, 'z': 1}

map的使用:

 根據提供的函數對指定序列做映射

def func(list_num):
    return list_num * 2

print(map(func, [1, 2, 3, 4, 5]))

result:
[2, 4, 6, 8, 10]

max的使用:

返回最大數值

ret = max(1, 10)
print(ret)

result:
10

memoryview的使用:

 返回給定參數的內存查看對象

v = memoryview(bytearray("abc", 'utf-8'))
print(v[0])

restlt:
97

min的使用:

 取出最小數值

print(min(1, 10))

result:
1

next的使用:

 返回迭代器的下一個項目

it = iter([1, 2, 3, 4, 5])
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration就退出循環
        break


result:
1
2
3
4
5

open的使用:

 打開一個文件,創建一個file對象,相關的方法才可以調用它的讀寫

f = open('test.txt')
f.read()
f.close()       # 文件讀寫完成之后,一定要關閉

ord的使用:

函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度為1的字符串)作為參數,返回對應的 ASCII 數值,或者 Unicode 數值,如果所給的 Unicode 字符超出了你的 Python 定義范圍,則會引發一個 TypeError 的異常。

ret = ord('a')
ret1 = ord('b')
ret2 = ord('c')


result:
97
98
99

pow的使用:

 返回 xy(x的y次方) 的值

import math   # 導入 math 模塊
 
print "math.pow(100, 2) : ", math.pow(100, 2)
# 使用內置,查看輸出結果區別
print "pow(100, 2) : ", pow(100, 2)
 
print "math.pow(100, -2) : ", math.pow(100, -2)
print "math.pow(2, 4) : ", math.pow(2, 4)
print "math.pow(3, 0) : ", math.pow(3, 0)

print的使用:

 輸出,打印

print('hello world')

result:
hello world

property的使用:

 新式類中的返回屬性值,python3中是新式類,2中是舊式類

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的使用:

輸出范圍之內的數值

for i in range(1, 5):
    print(i)

result:
1
2
3
4
5

repr的使用:

 函數將對象轉化為供解釋器讀取的形式

s = 'RUNOOB'
repr(s)
"'RUNOOB'"
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"

reversed的使用:

 返回一個反轉的迭代器

# 字符串
seqString = 'Runoob'
print(list(reversed(seqString)))
 
# 元組
seqTuple = ('R', 'u', 'n', 'o', 'o', 'b')
print(list(reversed(seqTuple)))
 
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
 
# 列表
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

result:
['b', 'o', 'o', 'n', 'u', 'R']
['b', 'o', 'o', 'n', 'u', 'R']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

round的使用:

 返回浮點數x的四舍五入值

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)

result:
round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0

set的使用:

 不可重復元素

a=set((1,2,3,"a","b"))

setattr的使用:

設置屬性值,該屬性必須存在

class A(object):
    bar = 1

a = A()
print(getattr(a, 'bar'))          # 獲取屬性 bar 值
1
setattr(a, 'bar', 5)      # 設置屬性 bar 值
print(a.bar)

slice的使用:

  實現切片對象,主要用在切片操作函數里的參數傳遞

myslice = slice(5)    # 設置截取5個元素的切片
print(myslice)
print(slice(None, 5, None))
arr = range(10)
print(arr)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(arr[myslice])        # 截取 5 個元素
[0, 1, 2, 3, 4]

 

sorted的使用:

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

a = [5,7,6,3,4,1,2]
b = sorted(a)       # 保留原列表
print(a) 
[5, 7, 6, 3, 4, 1, 2]
print(b)
[1, 2, 3, 4, 5, 6, 7]
 
L=[('b',2),('a',1),('c',3),('d',4)]
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函數
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
print(sorted(L, key=lambda x:x[1]))               # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
 
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
print(sorted(students, key=lambda s: s[2]) )           # 按年齡排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
print(sorted(students, key=lambda s: s[2], reverse=True) )      # 按降序
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

staticmethod的使用:

 返回函數的靜態方法

class C(object):
    @staticmethod
    def f():
        print('runoob');
 
C.f();          # 靜態方法無需實例化
cobj = C()
cobj.f()        # 也可以實例化后調用

str的使用:

 字符串

str = "wyc"

方法:
cpitalize      首字母變大寫

count           子序列個數

decode          解碼

encode          編碼針對unicode

endswith        是否以xxx結束

find            尋找子序列位置,如果沒有找到,返回-1

format          字符串格式化

index           子序列位置,如果沒有找到,報錯

isalnum         是否是字母數字

isalpha         是否是字母

isdigit         是否是數字

islower         是否小寫

join            拼接

lower           變小寫

lstrip          移除左側空白

replace         替換

sum的使用:

求數值整合

print(sum(1+1))

result:
2

super的使用:

 用於調用父類(超類)的一個方法

Python3.x 和 Python2.x 的一個區別是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx 

python3
class A:
    pass
class B(A):
    def add(self, x):
        super().add(x)

python2
class A(object):   # Python2.x 記得繼承 object
    pass
class B(A):
    def add(self, x):
        super(B, self).add(x)

tuple的使用:

元祖,元祖是不可修改的

tuple = (1, 2, 3)

type的使用:

查看當前類型是什么類型

lst = list()
print(type(lst))

result:
<class 'list'>

vars的使用:

 返回對象object的屬性和屬性值的字典對象

print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
class Runoob:
a = 1

print(vars(Runoob))
{'a': 1, '__module__': '__main__', '__doc__': None}
runoob = Runoob()
print(vars(runoob))
{}

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)]

__import__的使用:

 函數用於動態加載類和函數 

import  time, os

擴展進制轉換:

二進制轉換十進制

int('0b11', base=2)

result:    3

八進制轉換十進制

int('11', base=8)

result: 9

十六進制轉換十進制

int('0xe', base=16)

result: 14

以上有不足之處,請大神,留下寶貴的建議,本人看到第一時間添加。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM