Python初學(xué)者必須掌握的25個(gè)內(nèi)置函數(shù)詳解
input()
作用:讓用戶從控制臺(tái)輸入一串字符,按下回車后結(jié)束輸入,并返回字符串
注意:很多初學(xué)者以為它可以返回?cái)?shù)字,其實(shí)是錯(cuò)的!
>>> line = input("輸入一個(gè)數(shù)字:")
輸入一個(gè)數(shù)字:1
>>> line
'1' # <-- 看清楚了,這個(gè)不是數(shù)字,只是字符串
# 如果你直接進(jìn)行加法……
>>> line + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
# 正確方法,先把 line 轉(zhuǎn)換成數(shù)字
>>> int(line) + 1
2
print()
作用:把參數(shù)轉(zhuǎn)換成字符串后,輸出到控制臺(tái)
>>> print("hello", "world")
hello world
# 很多人不知道參數(shù)之間還可以插入其他字符
>>> print("hello", "world", sep="~")
hello~world
# 甚至可以讓每個(gè)參數(shù)霸占一行
>>> print("hello", "world", sep="\n")
hello
world
set()
作用:構(gòu)造集合。一個(gè)常用的方法是,把列表傳入 set(),再轉(zhuǎn)成列表,來實(shí)現(xiàn)列表的排重。
>>> set([1, 2, 3, 3])
{1, 2, 3}
# 這樣就實(shí)現(xiàn)了排重
>>> list(set([1, 2, 3, 3]))
[1, 2, 3]
str()
作用:將對(duì)象轉(zhuǎn)換成字符串。常用于字符串和數(shù)字的拼接。
例如,這樣會(huì)報(bào)錯(cuò):
>>> 'My Score is: ' + 100 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
所以要用 str 轉(zhuǎn)換一下:
>>> 'My Score is: ' + str(100) 'My Score is: 100'
chr(i)
作用:返回整數(shù) i 所對(duì)應(yīng)的字符,常用于生成字母表。
>>> chr(20013)
'中'
>>> chr(97)
'a'
# 與 ord() 配合,生成字母表
>>> [chr(ord('a') + i) for i in range(26)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
ord()
作用:返回字符在編碼表中對(duì)應(yīng)的十進(jìn)制數(shù)值
>>> ord('中')
20013
>>> ord('a')
97
# 與 chr() 配合,生成字母表
>>> [chr(ord('a') + i) for i in range(26)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
bool()
作用: 判斷一個(gè)對(duì)象的布爾值,返回 True 或 False
bool(1) => True bool(0) => False bool([]) => False
說明: 這個(gè)函數(shù)在實(shí)際項(xiàng)目中很少用,只是作為測(cè)試工具,讓初學(xué)者能了解各對(duì)象的布爾狀態(tài)。
int()
作用: 將任意進(jìn)制的字符串轉(zhuǎn)化為整數(shù)。
int('2') => 2
int('1010', 2) => 10 # 2進(jìn)制1010轉(zhuǎn)化為整數(shù)10
說明: 傳入第2個(gè)參數(shù),可指定參數(shù)1的進(jìn)制類型。
bin()
作用: 把整數(shù)轉(zhuǎn)換成2進(jìn)制的字符串
bin(2) => '0b10' bin(10) => '0b1010'
說明: 為啥字符串前面都有個(gè) 0b ?因?yàn)檫@是標(biāo)準(zhǔn)的寫法,以 0b 開頭表示接下來數(shù)字的是2進(jìn)制。
oct()
作用: 將10進(jìn)制轉(zhuǎn)換為8進(jìn)制的字符串
oct(7) => '0o7' oct(8) => '0o10'
hex()
作用:將10進(jìn)制轉(zhuǎn)換為16進(jìn)制的字符串
>>> hex(11) '0xb' >>> hex(16) '0x10'
abs()
作用:取絕對(duì)值
>>> abs(-1) 1
divmod()
作用:同時(shí)返回除法運(yùn)算中的商和余數(shù),相當(dāng)于一次運(yùn)算,同時(shí)得到 a//b 和 a% b 的結(jié)果。
>>> divmod(1, 2) (0, 1) >>> divmod(4, 3) (1, 1)
round()
作用:對(duì)一個(gè)浮點(diǎn)數(shù)進(jìn)行四舍五入
>>> round(1.3333) 1 >>> round(1.3333, 2) # 2 表示保留2位小數(shù) 1.33
pow(x, y[, z])
作用:如果只填 x 和 y 參數(shù),則返回 x 的 y 次方。如果填了 z 參數(shù),則再取模,相當(dāng)于 pow(x, y) % z。
>>> pow(10, 2) 100 # 相當(dāng)于 >>> 10**2 100 >>> pow(10, 2, 3) 1 # 相當(dāng)于 >>> 10**2 % 3 1
sum(iterable)
作用:對(duì)數(shù)組 iterable 的所有元素進(jìn)行求和。
>>> sum([1, 2, 3]) 6
min(x, y, z, …)
作用:返回所有參數(shù)中的最小數(shù)
>>> min(1, 2, 3) 1 # 傳入數(shù)組也可以 >>> min([1, 2, 3]) 1
max(x, y, z, …)
作用:類似 min(),返回所有參數(shù)中的最大數(shù)
list()
作用:傳入?yún)?shù)為空時(shí),創(chuàng)建列表;傳入?yún)?shù)不為空時(shí),將參數(shù)轉(zhuǎn)換成列表
>>> list()
[]
# 不為空時(shí)
>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
# 傳入字典試試
>>> list({'a': 1, 'b': 2})
['a', 'b']
tuple()
作用:跟 list 幾乎一模一樣,只不過 list 返回的是數(shù)組,tuple 返回的是元組。
dict()
作用:構(gòu)造字典
# 方法1:
>>> dict(a=1, b=2)
{'a': 1, 'b': 2}
# 方法2:
>>> dict(zip(['a', 'b'], [1, 2]))
{'a': 1, 'b': 2}
# 方法3:
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}
len()
作用:返回對(duì)象長(zhǎng)度,或元素個(gè)數(shù)
>>> len([1, 2])
2
>>> len({'a': 1, 'b': 2})
2
>>> len('hello')
5
reversed()
作用:反轉(zhuǎn)列表。
注意:返回的不是列表,是個(gè)迭代器。
>>> reversed([1, 2, 3])
<list_reverseiterator object at 0x1016190a0>
# 需要轉(zhuǎn)換成 list
>>> list(reversed([1, 2, 3]))
[3, 2, 1]
# 字符串也一樣
>>> reversed('abc')
<reversed object at 0x1015ffd90>
>>> list(reversed('abc'))
['c', 'b', 'a']
enumerate()
作用:用于遍歷對(duì)象,正常的遍歷,比如 for el in array ,只能拿到元素,不能拿到下標(biāo),用 enumerate() 就可以。
>>> for i, el in enumerate('abc'):
... print(i, el)
...
0 a
1 b
2 c
這個(gè)下標(biāo)怎么用呢?比如可以用來反過來修改數(shù)組內(nèi)的元素:
>>> alphabet = ['a', 'b', 'c'] >>> for i, el in enumerate(alphabet): ... alphabet[i] = el.upper() ... >>> alphabet ['A', 'B', 'C']
filter(func, iterable)
作用:過濾并返回符合條件的元素
注意:返回的是一個(gè)迭代器。
>>> alphabet = ['a', 'b', 'c', 'E', 'F', 'G'] >>> filter(lambda e: e.isupper(), alphabet) <filter object at 0x1016190a0> >>> list(filter(lambda e: e.isupper(), alphabet)) ['E', 'F', 'G']
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信