五個令人愉悅的 Python 函數(shù)
介紹5個有趣實用的python內(nèi)置函數(shù),enumerate、zip、__import__、accumulate、namedtuple。合理地使用,可以將代碼變的優(yōu)雅簡潔有趣!
今天給大家分享5個有趣實用的python內(nèi)置函數(shù),希望對你有所幫助!
enumerate函數(shù)
enumerate 函數(shù)可以將一個可迭代對象轉(zhuǎn)換為一個索引序列,同時在迭代過程中給出索引和對應(yīng)的元素。
基本用法:enumerate(iterable, start=0)
chessPieces = ["Pawns", "Rook", "Horse", "Bishops", "King", "Queen"]
for i in enumerate(chessPieces):
print(i)
## 輸出結(jié)果
# (0, "Pawns") # (1, "Rook") # (2, "Horse") # (3, "Bishops") # (4, "King") # (5, "Queen")
for i in enumerate(chessPieces, start=1):
print(i)
## 輸出結(jié)果
# (1, "Pawns") # (2, "Rook") # (3, "Horse") # (4, "Bishops") # (5, "King") # (6, "Queen")
zip函數(shù)
zip 函數(shù)可以將多個序列按順序合并為一個元組,同時迭代每個序列的所有元素。
基本用法:zip(*iterable, strict=False)
listOfUsers = ['a', 'b', 'c']
listOfRoles = ['admin', 'user', 'user']
for user, role in zip(listOfUsers, listOfRoles):
print(user, role) #輸出結(jié)果:a admin # b user # c user
raw = zip(*zip(listOfUsers, listOfRoles)) # 反轉(zhuǎn)
print(list(raw)) # [('a', 'b', 'c'), ('admin', 'user', 'user')]
# 長度不一致的情況
listOfUsers = ['a', 'b', 'c']
listOfRoles = ['admin', 'user']
for user, role in zip(listOfUsers, listOfRoles):
print(user, role) # 輸出結(jié)果:a admin # b user # c None
__import__動態(tài)導(dǎo)入
python動態(tài)加載模塊的好處是可以在不同的模塊之間共享模塊代碼,而不必每次都重新編譯。__import__ 函數(shù)可以實現(xiàn)動態(tài)加載模塊,并且可以訪問模塊中的類、函數(shù)、變量等。
基本用法:__import__(name, globals=None, locals=None, fromlist=(), level=0)
# 方法一:
import test # 加載模塊
testModule = __import__("test", globals(), locals(), [], 0) # 動態(tài)加載模塊
# 方法二
import test.test_support # 加載模塊
testModule = __import__("test.test_support", globals(), locals(), [], 0) # 動態(tài)加載模塊
# 方法三
from test import support # 加載模塊
testModule = __import__("test", globals(), locals(), ["support"], 0) # 動態(tài)加載模塊
accumulate累加函數(shù)
accumulate 函數(shù)可以將一個序列中的元素累積起來,返回一個新的序列。這兒的累積不僅僅是指元素相加法,也可以是乘法,甚至是自定義的運算。仔細學(xué)習(xí)下面的例子,不管是工作中,還是學(xué)習(xí)中,或許你會用到這個函數(shù)。
基本用法:accumulate(iterable, func=operator.add, *, initial=None)
from itertools import accumulate
import operator
def op(x, y):
return x + 3 * y
nums = [1, 2, 3, 4, 5]
print(list(accumulate(nums))) # 默認加法累積:[1, 3, 6, 10, 15]
print(list(accumulate(nums, operator.mul))) # 乘法累積:[1, 2, 6, 24, 120]
print(list(accumulate(nums, op))) # 自定義累積:[1, 7, 16, 28, 43]
# ??initial參數(shù)需要 python>=3.8
print(list(accumulate(nums, op, initial=2))) # 定義初始值
collections.namedtuple命名元組
namedtuple 函數(shù)可以將一個類似于元組的對象,轉(zhuǎn)換為一個可以訪問其元素的對象。簡單的說,給元組的每個值起個名字,然后可以通過名字訪問。
基本用法:collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
field_names 是一個字符串序列,例如 ['a','b'],也可以寫成 ['a b']。
from collections import namedtuple
data = (1, True, 'red') # 元組
name = ('value', 'enable', 'color') # 元組名
tupleData = namedtuple('dataVEC', name) # 定義一個名為dataVEC的元組
test = tupleData(*data) # 將data轉(zhuǎn)換為tuple類
print(test) # 輸出:dataVEC(value=1, enable=True, color='red')
print(test.value) # 輸出:1
print(test.enable) # 輸出:True
print(test.color) # 輸出:red
小節(jié)
今天我們介紹的五個函數(shù),你覺得哪個最有用?