Python 初學者必備的常用內置函數

本文綱要


Python 作為一門高級編程語言,為我們提供了許多方便易用的內置函數,節省了不少開發應用的時間。目前,Python 3.7 共有 69 個內置函數,一些是我們耳熟能詳的函數,另一些卻不是很常見,這裡主要介紹一些新手必備函數及其用法。


Python 初學者必備的常用內置函數


為了便於說明,我把這些內置函數粗略地分為六大類:


輸入輸出print() open() input()


迭代相關enumerate() zip()


序列屬性sum() max() min() len()


操作序列sorted() reversed() range()


對象屬性dir() id() isinstance() type()


映射類型eval() map() slice()


輸入輸出


print 函數將對象輸出至控制檯


<code>print(*objects, sep=' ', end='\\n', file=
sys.stdout, flush=False)/<code>


*objects 為可變參數,可以接受任意多個對象。sep 參數表示輸出對象之

間的分隔符,默認為空格。


<code>>>> print('Python', 'Python')
Python Python/<code>


分隔符為'*':


<code>>>> print('Python', 'Python', sep = '*')
Python*Python/<code>


格式化輸出字符串的三種方式:


<code>name = 'Python'
fmt1 = f'Python:{name}'
fmt2 = 'Python:{}'.format(name)
fmt3 = 'Python:%s' %name
print(fmt1)
print(fmt2)
print(fmt3)
/<code>


open 函數打開文件並返回文件對象

<code>open(file, mode='r', buffering=-1,encoding=None, errors=None, newline=None, closefd=True, opener=None)/<code>


file 為文件地址,mode 為打開文件的模式,默認為 'r',表示讀取文件,常用的還有:'w' 表示寫入文件、'b' 表示以二進制形式打開。

常用上下文管理器 with 打開文件,f.read( ) 讀取全部內容,f.readline() 讀取一行內容。


<code>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 == text2
print(text1)/<code>


有時候,我們讀取文件還會遇到亂碼問題,可以指定編碼格式:

當文件中有中文的時候,使用 'utf-8' 編碼會導致異常:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 7: invalid start byte


<code>with open('test.txt', 'r', 

       encoding='utf-8') as f:
   text1 = f.read()/<code>


這時候,我們可以嘗試 'gb2312' 或者 'gbk' 編碼來打開含有中文字符的文件。這時,便可以成功打開文件。


<code>with open('test.txt', 'r',
       encoding='gb2312') as f:
   text1 = f.read()

with open('test.txt', 'w',
       encoding='gbk') as f:
   f.write('Python')/<code>


input 函數獲取控制檯輸入


<code>input([prompt])/<code>


input 可接受字符串為參數,提示用戶輸入。


<code>>>> s = input('Python:')
Python:Python
>>> s
'Python'/<code>


迭代相關


enumerate 函數返回元素的序號與對應值


<code>enumerate(iterable, start=0)/<code>


iterable 參數表示可迭代對象,start 參數是元素序號的起點,默認為 0。

enumerate 函數的等價形式如下:


<code>def enumerate(sequence, start=0):
 n = start
 for elem in sequence:
     yield n, elem
     n += 1

seq = ['P', 'y', 't', 'h', 'o', 'n']for i, elem in enumerate(seq):
   print(i, elem)/<code>


zip 函數用於同時迭代多個對象



<code>zip(*iterables)/<code> 


*iterable 可以接受任意多個可迭代對象


<code>a = ["**", '**', '**']
b = ['Python', 'Python', 'Python']
c = a
print('#'*20)
for i, j, k in zip(a, b, c):
   print(i, j, k)
print('#'*20)


/<code>


序列屬性


序列最大值:max

序列最小值:min

序列的和: sum

序列長度: len


基本用法:向這四個函數中傳入序列,可以得到對應屬性。


<code>import random
random.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))
# 88
print(min(seq))
# 21
print(sum(seq))
# 545
print(len(seq))
# 10/<code>


作為內置函數,可以直接傳入生成器(不需要括號)作為參數:


<code>import random
random.seed(21)
num = max(random.randint(0, 100) for i in range(10))
print(num)
# 88/<code>


可傳入 key 參數,作為比較大小的依據,相當於把序列中每一個元素 item 先傳入函數 key 中,將函數返回的數值作為判斷對象大小的依據。


<code>def foo(x):
   return 1. / x
max(seq, key = foo)
# 21/<code>


對於我們自定義的類型,必須實現特殊方法,才能進行 len 等操作。

__len__ 代表:len 操作,__eq__ 代表:= 操作,__lt__ 代表 < 操作。


<code>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 < f2
True
>>> f1 > f2
False
>>> f1 == f2
False
>>> f3 = foo(18, [9, 9, 0, 7])
>>> f1 == f3
True
>>> len(f1)
3
>>> len(f2)
4/<code>


操作序列


range 函數生成序列


<code>range(start, stop[, step])/<code>


  • start 可選參數,默認為 0 ,表示序列起點
  • stop 必選參數,表示序列終點,不包括終點
  • step 可選參數,序列的步長,默認為 1


<code>>>> range(6)
range(0, 6)
>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(range(0, 6, 2))
[0, 2, 4]/<code>


range 函數生成的對象可以迭代,和列表很類似,_ 表示廢棄變量(為了避免汙染變量環境):


<code>for _ in range(3):
 print('Python')/<code>


reversed 函數可以將序列逆置


reversed 可以將序列逆置,包括元組、字符串、列表。對於列表和字符串的逆置,使用 list[::-1] 或者slice()更加方便。


<code>import random
random.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]/<code>


字符串逆置:


<code>>>> a = 'Python'
>>> a[::-1]
'Python'
>>> ''.join(reversed('Python'))
'Python'/<code>


sorted 函數可以對序列進行排序


<code>sorted(iterable, *, key=None, reverse=False)/<code> 


sorted 不同於 list.sort 操作(原地排序),返回一個新的有序序列,原序列保持不變。* 表示僅限關鍵字參數(keyword-only),也就是說,key、reverse 參數只能通過關鍵字傳參,而不能通過位置傳參。reverve 參數表示逆置操作,key 與之前 len 中的 key 參數類似,是函數排序的依據。


<code>>>> sorted([9, 6, 2, 3, 6])
[2, 3, 6, 6, 9]/<code>


對象屬性


dir 函數返回屬性列表

id 函數返回對象地址

isinstance 判斷對象的類型

type 返回對象的類型


<code>class foo:   pass>>> dir(foo)['__class__','__delattr__','__dict__','__dir__',......'__str__','__subclasshook__','__weakref__']# 創建實例>>> f = foo()>>> type(foo)__main__.foo>>> isinstance(f, foo)True>>> id(f)2135099584864/<code>


映射類型


eval 解除引號的束縛

map 應用函數於單個對象

slice 生成切片


eval 可以去除字符串的單引號,從而獲取引號內部內容。下面的演示展示了,如何使用 eval 函數獲取字符串中的字典:


<code>>>> info = '{"name": "LiHua", "age": 12}'
>>> eval(info)
{'name': 'LiHua', 'age': 12}
>>> info_dict = eval(info)
>>> type(info_dict)
dict/<code>


map 將傳進來的函數應用於序列中的每一個元素,並返回迭代器。


<code>map(function, iterable, ...)/<code>


舉例來說,map 就是對 seq 列表中的每一個元素 item 進行 int 操作(int(item))。匿名函數同理,就是對序列中的每一個元素進行加 2 的操作。


<code>>>> 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]/<code>


slice 函數為切片操作命名,使得切片操作更加清晰明瞭。


<code>slice(start, stop[, step])/<code>


start 為起點,stop 為終點,step 為步長。使用該操作,使得截取有規律的文本內容變得很輕鬆。特別是長文本,使用 slice 函數更加清晰易懂。


<code>>>> text = ' Python'
>>> name = slice(0, 6)
>>> text[name]
Python 
>>> content = slice(6, 16)
>>> text[content]
Python/<code>


這篇文章到此結束了,大家可以趁熱打鐵,多多練習。


分享到:


相關文章: