inrange函数_Python 初学者必备的常用内置函数
本文綱要
Python 作為一門高級(jí)編程語言,為我們提供了許多方便易用的內(nèi)置函數(shù),節(jié)省了不少開發(fā)應(yīng)用的時(shí)間。目前,Python 3.7 共有 69 個(gè)內(nèi)置函數(shù),一些是我們耳熟能詳?shù)暮瘮?shù),另一些卻不是很常見,這里主要介紹一些新手必備函數(shù)及其用法。
為了便于說明,我把這些內(nèi)置函數(shù)粗略地分為六大類:
輸入輸出print() open() input()
迭代相關(guān)enumerate() zip()
序列屬性sum() max() min() len()
操作序列sorted() reversed() range()
對(duì)象屬性dir() id() isinstance() type()
映射類型eval() map() slice()
輸入輸出
print 函數(shù)將對(duì)象輸出至控制臺(tái)
print(*objects, sep=' ', end='',?file=sys.stdout, flush=False)*objects 為可變參數(shù),可以接受任意多個(gè)對(duì)象。sep 參數(shù)表示輸出對(duì)象之
間的分隔符,默認(rèn)為空格。
>>> print('Python',?'Python')Python Python分隔符為'*':
>>> print('Python',?'Python', sep =?'*')Python*Python格式化輸出字符串的三種方式:
name =?'Python'fmt1 =?f'Python:{name}'fmt2 =?'Python:{}'.format(name)fmt3 =?'Python:%s'?%nameprint(fmt1)print(fmt2)print(fmt3)open 函數(shù)打開文件并返回文件對(duì)象
open(file, mode='r', buffering=-1,encoding=None, errors=None, newline=None, closefd=True, opener=None)file 為文件地址,mode 為打開文件的模式,默認(rèn)為 'r',表示讀取文件,常用的還有:'w' 表示寫入文件、'b' 表示以二進(jìn)制形式打開。
常用上下文管理器 with 打開文件,f.read( ) 讀取全部內(nèi)容,f.readline() 讀取一行內(nèi)容。
with?open('test.txt',?'r')PythonPythonPythonPythonPythonPythonPythonPython?as?f:? ?text1 = f.read()with?open('test.txt',?'r')?as?f:? ?text2 =?''? ?line = f.readline()? ?while?line:? ? ? ?text2 += line? ? ? ?line = f.readline()assert?text1 == text2print(text1)有時(shí)候,我們讀取文件還會(huì)遇到亂碼問題,可以指定編碼格式:
當(dāng)文件中有中文的時(shí)候,使用 'utf-8' 編碼會(huì)導(dǎo)致異常:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 7: invalid start byte
with?open('test.txt',?'r',? ? ? ?encoding='utf-8')?as?f:? ?text1 =?f.read()這時(shí)候,我們可以嘗試 'gb2312' 或者 'gbk' 編碼來打開含有中文字符的文件。這時(shí),便可以成功打開文件。
with?open('test.txt',?'r',? ? ? ?encoding='gb2312')?as?f:? ?text1 =?f.read()with?open('test.txt',?'w',? ? ? ?encoding='gbk')?as?f:? ?f.write('Python')input 函數(shù)獲取控制臺(tái)輸入
input([prompt])input 可接受字符串為參數(shù),提示用戶輸入。
>>>?s = input('Python:')Python:Python>>>?s'Python'迭代相關(guān)
enumerate 函數(shù)返回元素的序號(hào)與對(duì)應(yīng)值
enumerate(iterable, start=0)iterable 參數(shù)表示可迭代對(duì)象,start 參數(shù)是元素序號(hào)的起點(diǎn),默認(rèn)為 0。
enumerate 函數(shù)的等價(jià)形式如下:
def?enumerate(sequence, start=0):?n = start?for?elem?in?sequence:? ? ?yield?n, elem? ? ?n +=?1seq =?['P',?'y',?'t',?'h',?'o',?'n']for?i, elem?in?enumerate(seq):? ?print(i, elem)zip 函數(shù)用于同時(shí)迭代多個(gè)對(duì)象
zip(*iterables)*iterable 可以接受任意多個(gè)可迭代對(duì)象
a = ["**",?'**',?'**']b = ['Python',?'Python',?'Python']c = aprint('#'*20)for?i, j, k?in?zip(a, b, c):? ?print(i, j, k)print('#'*20)序列屬性
序列最大值:max
序列最小值:min
序列的和: sum
序列長度: len
基本用法:向這四個(gè)函數(shù)中傳入序列,可以得到對(duì)應(yīng)屬性。
import?randomrandom.seed(21)seq = [random.randint(0,?100)?for?i?in?range(10)]print(seq)# [21, 53, 88, 53, 81, 36, 61, 27, 60, 65]print(max(seq))# 88print(min(seq))# 21print(sum(seq))# 545print(len(seq))# 10作為內(nèi)置函數(shù),可以直接傳入生成器(不需要括號(hào))作為參數(shù):
import?randomrandom.seed(21)num = max(random.randint(0,?100)?for?i?in?range(10))print(num)# 88可傳入 key 參數(shù),作為比較大小的依據(jù),相當(dāng)于把序列中每一個(gè)元素 item 先傳入函數(shù) key 中,將函數(shù)返回的數(shù)值作為判斷對(duì)象大小的依據(jù)。
def?foo(x):? ?return?1.?/ xmax(seq, key = foo)# 21對(duì)于我們自定義的類型,必須實(shí)現(xiàn)特殊方法,才能進(jìn)行 len 等操作。
__len__ 代表:len 操作,__eq__ 代表:= 操作,__lt__ 代表 < 操作。
class?foo:? ?def?__init__(self, num, seq):? ? ? ?self.num = num? ? ? ?self.seq = seq? ? ? ?? ?def?__len__(self):? ? ? ?return?len(self.seq)? ? ? ?? ?def?__eq__(self, other):? ? ? ?return?self.num == other.num? ? ? ?? ?def?__lt__(self, other):? ? ? ?return?self.num < other.num>>> f1 = foo(18, [1,?4,?6])>>> f2 = foo(21, [1,?7,?9,?10])>>> f1 < f2True>>> f1 > f2False>>> f1 == f2False>>> f3 = foo(18, [9,?9,?0,?7])>>> f1 == f3True>>> len(f1)3>>> len(f2)4操作序列
range 函數(shù)生成序列
range(start, stop[, step])- start 可選參數(shù),默認(rèn)為 0 ,表示序列起點(diǎn)
- stop 必選參數(shù),表示序列終點(diǎn),不包括終點(diǎn)
- step 可選參數(shù),序列的步長,默認(rèn)為 1
range 函數(shù)生成的對(duì)象可以迭代,和列表很類似,_ 表示廢棄變量(為了避免污染變量環(huán)境):
for?_ in?range(3):?print('Python')reversed 函數(shù)可以將序列逆置
reversed 可以將序列逆置,包括元組、字符串、列表。對(duì)于列表和字符串的逆置,使用 list[::-1] 或者slice()更加方便。
import?randomrandom.seed(21)seq = [random.randint(0,?100)?for?i?in?range(10)]print(seq)# [21, 53, 88, 53, 81, 36, 61, 27, 60, 65]reversed(seq)print(list(reversed(seq)))# [65, 60, 27, 61, 36, 81, 53, 88, 53, 21]字符串逆置:
>>> a?=?'Python'>>> a[::-1]'Python'>>>?''.join(reversed('Python'))'Python'sorted 函數(shù)可以對(duì)序列進(jìn)行排序
sorted(iterable, *, key=None, reverse=False)sorted 不同于 list.sort 操作(原地排序),返回一個(gè)新的有序序列,原序列保持不變。* 表示僅限關(guān)鍵字參數(shù)(keyword-only),也就是說,key、reverse 參數(shù)只能通過關(guān)鍵字傳參,而不能通過位置傳參。reverve 參數(shù)表示逆置操作,key 與之前 len 中的 key 參數(shù)類似,是函數(shù)排序的依據(jù)。
>>> sorted([9,?6,?2,?3,?6])[2, 3, 6, 6, 9]對(duì)象屬性
dir 函數(shù)返回屬性列表
id 函數(shù)返回對(duì)象地址
isinstance 判斷對(duì)象的類型
type 返回對(duì)象的類型
class?foo:? ?pass>>> dir(foo)['__class__','__delattr__','__dict__','__dir__',......'__str__','__subclasshook__','__weakref__']# 創(chuàng)建實(shí)例>>> f = foo()>>> type(foo)__main__.foo>>> isinstance(f, foo)True>>> id(f)2135099584864映射類型
eval 解除引號(hào)的束縛
map 應(yīng)用函數(shù)于單個(gè)對(duì)象
slice 生成切片
eval 可以去除字符串的單引號(hào),從而獲取引號(hào)內(nèi)部內(nèi)容。下面的演示展示了,如何使用 eval 函數(shù)獲取字符串中的字典:
>>> info =?'{"name": "LiHua", "age": 12}'>>> eval(info){'name':?'LiHua',?'age':?12}>>> info_dict = eval(info)>>> type(info_dict)dictmap 將傳進(jìn)來的函數(shù)應(yīng)用于序列中的每一個(gè)元素,并返回迭代器。
map(function,?iterable, ...)舉例來說,map 就是對(duì) seq 列表中的每一個(gè)元素 item 進(jìn)行 int 操作(int(item))。匿名函數(shù)同理,就是對(duì)序列中的每一個(gè)元素進(jìn)行加 2 的操作。
>>>?seq = [1.5,?4.5,?9.1]>>> list(map(int, seq))[1, 4, 9]>>> list(map(lambda?x:?x?+?2, seq))[3.5, 6.5, 11.1]slice 函數(shù)為切片操作命名,使得切片操作更加清晰明了。
slice(start,?stop[, step])start 為起點(diǎn),stop 為終點(diǎn),step 為步長。使用該操作,使得截取有規(guī)律的文本內(nèi)容變得很輕松。特別是長文本,使用 slice 函數(shù)更加清晰易懂。
>>> text =?' Python'>>> name = slice(0,?6)>>> text[name]Python?>>> content = slice(6,?16)>>> text[content]Python這篇文章到此結(jié)束了,大家可以趁熱打鐵,多多練習(xí)。
總結(jié)
以上是生活随笔為你收集整理的inrange函数_Python 初学者必备的常用内置函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中介贷款服务费合法吗
- 下一篇: python多线程怎么写日志_Pytho