Python基礎(chǔ)入門之len、abs、sum等內(nèi)置函數(shù)使用匯總
一、開篇:Python的內(nèi)置函數(shù)
Python自帶70多個內(nèi)置函數(shù)(Built-in Functions),——不需要import,隨時可用,覆蓋了類型轉(zhuǎn)換、數(shù)學(xué)計算、序列操作、對象信息等方方面面。
你已經(jīng)在日常編程中大量使用它們了:
# 這些你不用import就能用:
print(len([1, 2, 3])) # 3
print(abs(-5)) # 5
print(sum([1, 2, 3])) # 6
print(type("hello")) # <class 'str'>
print(int("42")) # 42
print(range(10)) # range(0, 10)
print(isinstance(5, int)) # True
這篇文章,我們對Python內(nèi)置函數(shù)做一個系統(tǒng)性的梳理——按類別整理,了解每個函數(shù)的用途和典型用法。這不只是一份"速查表",更是幫你建立Python全局視野的指南。
二、數(shù)學(xué)相關(guān)內(nèi)置函數(shù)
2.1 基本數(shù)學(xué)運算
# abs(x) —— 絕對值
print(abs(-10)) # 10
print(abs(3.14)) # 3.14
print(abs(-3 + 4j)) # 5.0 —— 復(fù)數(shù)的模
# round(number, ndigits) —— 四舍五入
print(round(3.14159, 2)) # 3.14
print(round(3.14159)) # 3(不指定精度,保留到整數(shù))
print(round(2.5)) # 2 —— ?? 注意:銀行家舍入!
# pow(base, exp, mod) —— 冪運算(可帶模)
print(pow(2, 10)) # 1024
print(pow(2, 10, 1000)) # 24 —— 等價于 (2**10) % 1000,但更高效
# divmod(a, b) —— 同時返回商和余數(shù)
quotient, remainder = divmod(17, 5)
print(f"17 ÷ 5 = {quotient} 余 {remainder}") # 17 ÷ 5 = 3 余 2
# 常用于:分頁計算、時間換算
total_minutes = 137
hours, minutes = divmod(total_minutes, 60)
print(f"{hours}小時{minutes}分鐘") # 2小時17分鐘
2.2 聚合函數(shù)
# sum(iterable, start) —— 求和
print(sum([1, 2, 3, 4, 5])) # 15
print(sum([1, 2, 3], 10)) # 16(從10開始加)
# 性能提示:sum()用C實現(xiàn),比for循環(huán)快得多
# min(iterable) / min(a, b, c, ...) —— 最小值
print(min([5, 2, 8, 1, 9])) # 1
print(min(5, 2, 8, 1, 9)) # 1
print(min("python", "java", "c")) # 'c' —— 按字母順序
# min也支持key參數(shù)
words = ["python", "java", "c", "go", "rust"]
print(min(words, key=len)) # 'c' —— 最短的
# max(iterable) —— 最大值
print(max([5, 2, 8, 1, 9])) # 9
print(max(words, key=len)) # 'python' —— 最長的
# 實用組合
scores = [85, 92, 78, 95, 88]
avg = sum(scores) / len(scores)
print(f"平均分: {avg:.1f}, 最高: {max(scores)}, 最低: {min(scores)}")
三、類型轉(zhuǎn)換內(nèi)置函數(shù)
3.1 數(shù)值類型轉(zhuǎn)換
# int(x, base) —— 轉(zhuǎn)整數(shù)
print(int(3.14)) # 3
print(int("42")) # 42
print(int("1010", 2)) # 10 —— 二進制字符串轉(zhuǎn)十進制
print(int("FF", 16)) # 255 —— 十六進制
print(int("0xFF", 16)) # 255 —— 0x前綴也能處理
# float(x) —— 轉(zhuǎn)浮點數(shù)
print(float(42)) # 42.0
print(float("3.14")) # 3.14
print(float("inf")) # inf —— 無窮大
print(float("nan")) # nan —— 非數(shù)字
# complex(real, imag) —— 轉(zhuǎn)復(fù)數(shù)
print(complex(3, 4)) # (3+4j)
print(complex("3+4j")) # (3+4j)
# bool(x) —— 轉(zhuǎn)布爾值
print(bool(1)) # True
print(bool(0)) # False
print(bool([])) # False —— 空列表是假值
print(bool([1, 2])) # True
print(bool("hello")) # True
print(bool("")) # False
3.2 序列類型轉(zhuǎn)換
# list(iterable) —— 轉(zhuǎn)列表
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list((1, 2, 3))) # [1, 2, 3]
# tuple(iterable) —— 轉(zhuǎn)元組
print(tuple([1, 2, 3])) # (1, 2, 3)
# set(iterable) —— 轉(zhuǎn)集合(自動去重)
print(set([1, 2, 2, 3, 3, 3])) # {1, 2, 3}
# dict(**kwargs) 或 dict(mapping) —— 創(chuàng)建字典
print(dict(name="張三", age=25)) # {'name': '張三', 'age': 25}
print(dict([("a", 1), ("b", 2)])) # {'a': 1, 'b': 2}
# frozenset(iterable) —— 不可變集合
fs = frozenset([1, 2, 3])
# fs.add(4) # AttributeError! 不可修改
# str(object) —— 轉(zhuǎn)字符串
print(str(42)) # "42"
print(str([1, 2, 3])) # "[1, 2, 3]"
print(str(None)) # "None"
# bytes(source) —— 創(chuàng)建字節(jié)對象
print(bytes([72, 101, 108, 108, 111])) # b'Hello'
print(bytes("Hello", "utf-8")) # b'Hello'
# bytearray(source) —— 可變的字節(jié)數(shù)組
ba = bytearray(b"Hello")
ba[0] = 104 # 'h'的ASCII碼
print(ba) # bytearray(b'hello')
四、序列操作內(nèi)置函數(shù)
4.1 信息獲取
# len(s) —— 獲取長度
print(len("Python")) # 6
print(len([1, 2, 3, 4, 5])) # 5
print(len({"a": 1, "b": 2})) # 2
# ?? len()是O(1)操作——Python內(nèi)部記錄了長度
4.2 創(chuàng)建和轉(zhuǎn)換序列
# range(start, stop, step) —— 創(chuàng)建整數(shù)序列
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# enumerate(iterable, start) —— 帶索引的迭代
fruits = ["蘋果", "香蕉", "橙子"]
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# 1. 蘋果
# 2. 香蕉
# 3. 橙子
# zip(*iterables) —— 并行迭代
names = ["張三", "李四", "王五"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 張三: 85
# 李四: 92
# 王五: 78
# 矩陣轉(zhuǎn)置(zip的經(jīng)典應(yīng)用)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(transposed) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# reversed(sequence) —— 反向迭代
print(list(reversed([1, 2, 3, 4]))) # [4, 3, 2, 1]
print("".join(reversed("Hello"))) # 'olleH'
# sorted(iterable, key, reverse) —— 排序
print(sorted([3, 1, 4, 1, 5])) # [1, 1, 3, 4, 5]
# slice(start, stop, step) —— 創(chuàng)建切片對象
s = slice(1, 5, 2)
print([0, 1, 2, 3, 4, 5, 6, 7, 8, 9][s]) # [1, 3]
# filter(function, iterable) —— 過濾
# map(function, iterable) —— 映射
五、對象信息內(nèi)置函數(shù)
5.1 類型和身份檢查
# type(object) —— 獲取類型
print(type(42)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
# isinstance(object, classinfo) —— 檢查是否為某類型
print(isinstance(42, int)) # True
print(isinstance(42, (int, float))) # True —— 可以是多個類型之一
print(isinstance("hello", str)) # True
print(isinstance([1, 2], (list, tuple))) # True
# issubclass(class, classinfo) —— 檢查子類關(guān)系
class Animal: pass
class Dog(Animal): pass
print(issubclass(Dog, Animal)) # True
print(issubclass(Dog, object)) # True
# id(object) —— 獲取對象的內(nèi)存地址
a = [1, 2, 3]
b = a
print(id(a)) # 例如: 140234567890
print(id(b)) # 相同——同一個對象
print(id([1, 2, 3])) # 不同——新創(chuàng)建的對象
# hash(object) —— 獲取哈希值
print(hash("hello")) # 某個整數(shù)
print(hash((1, 2, 3))) # 某個整數(shù)
# hash([1, 2, 3]) # TypeError! 列表不可哈希
5.2 屬性和能力檢查
# dir(object) —— 列出對象的所有屬性和方法
print(dir("hello")) # 列出字符串的所有方法
print(dir([])) # 列出列表的所有方法
# hasattr(obj, name) —— 檢查是否有某屬性
print(hasattr("hello", "upper")) # True
print(hasattr("hello", "foo")) # False
# getattr(obj, name, default) —— 獲取屬性
print(getattr("hello", "upper")) # <built-in method upper>
print(getattr("hello", "foo", None)) # None —— 不存在返回默認值
# setattr(obj, name, value) —— 設(shè)置屬性
class Config: pass
cfg = Config()
setattr(cfg, "debug", True)
print(cfg.debug) # True
# callable(object) —— 檢查是否為可調(diào)用對象
print(callable(print)) # True —— 函數(shù)可調(diào)用
print(callable(lambda: 1)) # True —— lambda可調(diào)用
print(callable(42)) # False —— 數(shù)字不可調(diào)用
print(callable("hello")) # False —— 字符串不可調(diào)用
六、I/O和字符串相關(guān)
6.1 輸入輸出
# print(*objects, sep, end, file, flush)
print("Hello", "World", sep=", ", end="!\n")
# Hello, World!
# 打印到文件
# with open("output.txt", "w") as f:
# print("日志信息", file=f)
# input(prompt) —— 獲取用戶輸入
# name = input("請輸入你的名字: ")
# age = int(input("請輸入你的年齡: "))
# open(file, mode, ...) —— 打開文件
# with open("data.txt", "r", encoding="utf-8") as f:
# content = f.read()
6.2 字符編碼和格式化
# ord(c) —— 字符轉(zhuǎn)Unicode碼點
print(ord('A')) # 65
print(ord('中')) # 20013
print(ord('??')) # 128512
# chr(i) —— Unicode碼點轉(zhuǎn)字符
print(chr(65)) # 'A'
print(chr(20013)) # '中'
print(chr(128512)) # '??'
# repr(object) —— 獲取對象的表示形式
print(repr("Hello\nWorld")) # 'Hello\nWorld'
# ascii(object) —— ASCII表示(非ASCII字符轉(zhuǎn)義)
print(ascii("Hello 世界")) # 'Hello 世界'
# format(value, format_spec) —— 格式化
print(format(255, 'x')) # 'ff' —— 十六進制
print(format(255, '#x')) # '0xff'
print(format(3.14159, '.2f')) # '3.14'
# bin(x), oct(x), hex(x) —— 進制轉(zhuǎn)換
print(bin(10)) # '0b1010'
print(oct(10)) # '0o12'
print(hex(255)) # '0xff'
七、函數(shù)式編程內(nèi)置函數(shù)
# iter(iterable) —— 獲取迭代器 it = iter([1, 2, 3]) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 # next(iterator, default) —— 獲取下一個元素 it = iter([1]) print(next(it, "default")) # 1 print(next(it, "default")) # 'default' —— 迭代器耗盡 # any(iterable) —— 任一為True print(any([False, False, True])) # True print(any([0, "", None, False])) # False # all(iterable) —— 全部為True print(all([True, True, True])) # True print(all([True, False, True])) # False
八、最常用的內(nèi)置函數(shù)Top 10
根據(jù)使用頻率排名
- print() —— 輸出
- len() —— 獲取長度
- type() —— 查看類型
- int() / str() / float() —— 類型轉(zhuǎn)換
- range() —— 生成序列
- list() / dict() / tuple() / set() —— 創(chuàng)建容器
- input() —— 獲取輸入
- enumerate() / zip() —— 序列操作
- isinstance() —— 類型檢查
- sorted() / min() / max() / sum() —— 聚合
熟練掌握這10類函數(shù),能覆蓋日常編程90%的需求
九、總結(jié)
Python的70+內(nèi)置函數(shù)是語言設(shè)計哲學(xué)"電池已包含"(Batteries Included)的體現(xiàn)。它們覆蓋了數(shù)學(xué)計算、類型轉(zhuǎn)換、序列操作、對象信息、I/O、編碼轉(zhuǎn)換等方方面面。
使用建議:
- 優(yōu)先使用內(nèi)置函數(shù)——C實現(xiàn),速度快,bug少
- 了解但不死記——知道有哪些就行,需要時查
- 善用內(nèi)置函數(shù)組合——
sum(map(int, data))之類的鏈式調(diào)用
以上就是Python基礎(chǔ)入門之len、abs、sum等內(nèi)置函數(shù)使用匯總的詳細內(nèi)容,更多關(guān)于Python內(nèi)置函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決tf.keras.models.load_model加載模型報錯問題
這篇文章主要介紹了解決tf.keras.models.load_model加載模型報錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
在交互式環(huán)境中執(zhí)行Python程序過程詳解
這篇文章主要介紹了在交互式環(huán)境中執(zhí)行Python程序過程詳解,運行Python腳本程序的方式有多種,目前主要的方式有:交互式環(huán)境運行、命令行窗口運行、開發(fā)工具上運行等,其中在不同的操作平臺上還互不相同,需要的朋友可以參考下2019-07-07
用Python將Excel數(shù)據(jù)導(dǎo)入到SQL Server的例子
今天小編就為大家分享一篇用Python將Excel數(shù)據(jù)導(dǎo)入到SQL Server的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
使用Python中的reduce()函數(shù)求積的實例
今天小編就為大家分享一篇使用Python中的reduce()函數(shù)求積的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
瘋狂上漲的Python 開發(fā)者應(yīng)從2.x還是3.x著手?
熱度瘋漲的 Python,開發(fā)者應(yīng)從 2.x 還是 3.x 著手?這篇文章就為大家分析一下了Python開發(fā)者應(yīng)從2.x還是3.x學(xué)起,感興趣的小伙伴們可以參考一下2017-11-11

