最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python基礎(chǔ)入門之len、abs、sum等內(nèi)置函數(shù)使用匯總

 更新時(shí)間:2026年07月26日 09:20:51   作者:星河耀銀海  
本文系統(tǒng)梳理了Python自帶的70多個(gè)內(nèi)置函數(shù),涵蓋數(shù)學(xué)計(jì)算、類型轉(zhuǎn)換、序列操作等類別,幫你建立全局視野,不再死記硬背,掌握這些函數(shù)讓你的代碼更簡(jiǎn)潔高效,是每個(gè)Python開發(fā)者必備的速查指南

一、開篇:Python的內(nèi)置函數(shù)

Python自帶70多個(gè)內(nèi)置函數(shù)(Built-in Functions),——不需要import,隨時(shí)可用,覆蓋了類型轉(zhuǎn)換、數(shù)學(xué)計(jì)算、序列操作、對(duì)象信息等方方面面。

你已經(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

這篇文章,我們對(duì)Python內(nèi)置函數(shù)做一個(gè)系統(tǒng)性的梳理——按類別整理,了解每個(gè)函數(shù)的用途和典型用法。這不只是一份"速查表",更是幫你建立Python全局視野的指南。

二、數(shù)學(xué)相關(guān)內(nèi)置函數(shù)

2.1 基本數(shù)學(xué)運(yùn)算

# abs(x) —— 絕對(duì)值
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) —— 冪運(yùn)算(可帶模)
print(pow(2, 10))          # 1024
print(pow(2, 10, 1000))    # 24 —— 等價(jià)于 (2**10) % 1000,但更高效

# divmod(a, b) —— 同時(shí)返回商和余數(shù)
quotient, remainder = divmod(17, 5)
print(f"17 ÷ 5 = {quotient} 余 {remainder}")  # 17 ÷ 5 = 3 余 2
# 常用于:分頁計(jì)算、時(shí)間換算
total_minutes = 137
hours, minutes = divmod(total_minutes, 60)
print(f"{hours}小時(shí){minutes}分鐘")  # 2小時(shí)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實(shí)現(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' —— 最長(zhǎng)的

# 實(shí)用組合
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 —— 二進(jìn)制字符串轉(zhuǎn)十進(jìn)制
print(int("FF", 16))       # 255 —— 十六進(jìn)制
print(int("0xFF", 16))     # 255 —— 0x前綴也能處理

# float(x) —— 轉(zhuǎn)浮點(diǎ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)集合(自動(dòng)去重)
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é)對(duì)象
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) —— 獲取長(zhǎng)度
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)部記錄了長(zhǎng)度

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)建切片對(duì)象
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) —— 映射

五、對(duì)象信息內(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 —— 可以是多個(gè)類型之一
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) —— 獲取對(duì)象的內(nèi)存地址
a = [1, 2, 3]
b = a
print(id(a))   # 例如: 140234567890
print(id(b))   # 相同——同一個(gè)對(duì)象
print(id([1, 2, 3]))  # 不同——新創(chuàng)建的對(duì)象

# hash(object) —— 獲取哈希值
print(hash("hello"))     # 某個(gè)整數(shù)
print(hash((1, 2, 3)))   # 某個(gè)整數(shù)
# hash([1, 2, 3])  # TypeError! 列表不可哈希

5.2 屬性和能力檢查

# dir(object) —— 列出對(duì)象的所有屬性和方法
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 —— 不存在返回默認(rèn)值

# setattr(obj, name, value) —— 設(shè)置屬性
class Config: pass
cfg = Config()
setattr(cfg, "debug", True)
print(cfg.debug)  # True

# callable(object) —— 檢查是否為可調(diào)用對(duì)象
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("請(qǐng)輸入你的名字: ")
# age = int(input("請(qǐng)輸入你的年齡: "))

# open(file, mode, ...) —— 打開文件
# with open("data.txt", "r", encoding="utf-8") as f:
#     content = f.read()

6.2 字符編碼和格式化

# ord(c) —— 字符轉(zhuǎn)Unicode碼點(diǎn)
print(ord('A'))    # 65
print(ord('中'))   # 20013
print(ord('??'))   # 128512

# chr(i) —— Unicode碼點(diǎn)轉(zhuǎn)字符
print(chr(65))     # 'A'
print(chr(20013))  # '中'
print(chr(128512)) # '??'

# repr(object) —— 獲取對(duì)象的表示形式
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' —— 十六進(jìn)制
print(format(255, '#x'))    # '0xff'
print(format(3.14159, '.2f'))  # '3.14'

# bin(x), oct(x), hex(x) —— 進(jìn)制轉(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) —— 獲取下一個(gè)元素
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() —— 獲取長(zhǎng)度
  • 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è)計(jì)哲學(xué)"電池已包含"(Batteries Included)的體現(xiàn)。它們覆蓋了數(shù)學(xué)計(jì)算、類型轉(zhuǎn)換、序列操作、對(duì)象信息、I/O、編碼轉(zhuǎn)換等方方面面。

使用建議:

  1. 優(yōu)先使用內(nèi)置函數(shù)——C實(shí)現(xiàn),速度快,bug少
  2. 了解但不死記——知道有哪些就行,需要時(shí)查
  3. 善用內(nèi)置函數(shù)組合——sum(map(int, data)) 之類的鏈?zhǔn)秸{(diào)用

以上就是Python基礎(chǔ)入門之len、abs、sum等內(nèi)置函數(shù)使用匯總的詳細(xì)內(nèi)容,更多關(guān)于Python內(nèi)置函數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python多線程與同步機(jī)制淺析

    Python多線程與同步機(jī)制淺析

    線程(Thread)是操作系統(tǒng)能夠進(jìn)行運(yùn)算調(diào)度的最小單位;線程自己不擁有系統(tǒng)資源,只擁有一點(diǎn)兒在運(yùn)行中必不可少的資源,但它可與同屬一個(gè)進(jìn)程的其它線程共享進(jìn)程所擁有的全部資源
    2022-12-12
  • 解決tf.keras.models.load_model加載模型報(bào)錯(cuò)問題

    解決tf.keras.models.load_model加載模型報(bào)錯(cuò)問題

    這篇文章主要介紹了解決tf.keras.models.load_model加載模型報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 使用Python來做一個(gè)屏幕錄制工具的操作代碼

    使用Python來做一個(gè)屏幕錄制工具的操作代碼

    本文給大家分享使用Python來做一個(gè)屏幕錄制工具,通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-01-01
  • 在交互式環(huán)境中執(zhí)行Python程序過程詳解

    在交互式環(huán)境中執(zhí)行Python程序過程詳解

    這篇文章主要介紹了在交互式環(huán)境中執(zhí)行Python程序過程詳解,運(yùn)行Python腳本程序的方式有多種,目前主要的方式有:交互式環(huán)境運(yùn)行、命令行窗口運(yùn)行、開發(fā)工具上運(yùn)行等,其中在不同的操作平臺(tái)上還互不相同,需要的朋友可以參考下
    2019-07-07
  • Python查詢阿里巴巴關(guān)鍵字排名的方法

    Python查詢阿里巴巴關(guān)鍵字排名的方法

    這篇文章主要介紹了Python查詢阿里巴巴關(guān)鍵字排名的方法,涉及Python基于urllib模塊解析html頁面及進(jìn)行URL查詢的相關(guān)技巧,需要的朋友可以參考下
    2015-07-07
  • python3 拼接字符串的7種方法

    python3 拼接字符串的7種方法

    本文給大家羅列了python3拼接字符串的七種方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2018-09-09
  • 用Python將Excel數(shù)據(jù)導(dǎo)入到SQL Server的例子

    用Python將Excel數(shù)據(jù)導(dǎo)入到SQL Server的例子

    今天小編就為大家分享一篇用Python將Excel數(shù)據(jù)導(dǎo)入到SQL Server的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 使用Python中的reduce()函數(shù)求積的實(shí)例

    使用Python中的reduce()函數(shù)求積的實(shí)例

    今天小編就為大家分享一篇使用Python中的reduce()函數(shù)求積的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • 在python中畫正態(tài)分布圖像的實(shí)例

    在python中畫正態(tài)分布圖像的實(shí)例

    今天小編就為大家分享一篇在python中畫正態(tài)分布圖像的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 瘋狂上漲的Python 開發(fā)者應(yīng)從2.x還是3.x著手?

    瘋狂上漲的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

最新評(píng)論

文安县| 禄丰县| 什邡市| 温泉县| 康马县| 朝阳县| 武安市| 吉木乃县| 九江县| 东乌珠穆沁旗| 台北市| 井冈山市| 凤凰县| 南岸区| 永仁县| 东至县| 基隆市| 大冶市| 中方县| 惠东县| 阳春市| 禹州市| 许昌市| 迭部县| 社会| 寿光市| 敦煌市| 南充市| 房产| 淮北市| 凭祥市| 山东省| 石阡县| 冀州市| 林甸县| 湘潭县| 阜新| 无为县| 吉安县| 黄梅县| 南皮县|