Python中很常用的100個函數整理

Python 內置函數提供了強大的工具,涵蓋數據處理、數學運算、迭代控制、類型轉換等。本文總結了 100 個常用內置函數,并配備示例代碼,提高編程效率。

1. abs() 取絕對值

print(abs(-10)) ?# 10

2. all() 判斷所有元素是否為真

print(all([True, 1, "hello"])) ?# True
print(all([True, 0, "hello"])) ?# False

3. any() 判斷任意元素是否為真

print(any([False, 0, "", None])) ?# False
print(any([False, 1, ""])) ?# True

4. ascii() 返回對象的 ASCII 表示

print(ascii("你好")) ?# '\u4f60\u597d'

5. bin() 十進制轉二進制

print(bin(10)) ?# '0b1010'

6. bool() 轉換為布爾值

print(bool([])) ?# False
print(bool(1)) ?# True

7. bytearray() 創建字節數組

ba = bytearray([65, 66, 67])
print(ba) ?# bytearray(b'ABC')

8. bytes() 創建不可變字節序列

b = bytes("hello", encoding="utf-8")
print(b) ?# b'hello'

9. callable() 判斷對象是否可調用

def func(): pass
print(callable(func)) ?# True
print(callable(10)) ?# False

10. chr() 獲取 Unicode 碼對應的字符

print(chr(97)) ?# 'a'

11. ord() 獲取字符的 Unicode 編碼

print(ord('a')) ?# 97

12. complex() 創建復數

print(complex(1, 2)) ?# (1+2j)

13. dict() 創建字典

d = dict(name="Alice", age=25)
print(d) ?# {'name': 'Alice', 'age': 25}

14. dir() 獲取對象所有屬性和方法

print(dir([])) ?# ['append', 'clear', 'copy', ...]

15. divmod() 取商和余數

print(divmod(10, 3)) ?# (3, 1)

16. enumerate() 生成索引和值

lst = ["a", "b", "c"]
for i, v in enumerate(lst):print(i, v)

17. eval() 計算字符串表達式

expr = "3 + 4"
print(eval(expr)) ?# 7

18. filter() 過濾序列

nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) ?# [2, 4]

19. float() 轉換為浮點數

print(float("3.14")) ?# 3.14

20. format() 格式化字符串

print(format(10000, ",")) ?# '10,000'
21. frozenset() 創建不可變集合
fs = frozenset([1, 2, 3])
print(fs)

22. globals() 獲取全局變量

print(globals())

23. hasattr() 檢查對象是否有屬性

class Person:name = "Alice"print(hasattr(Person, "name")) ?# True

24. hash() 獲取哈希值

print(hash("hello")) ?

25. help() 查看幫助

help(print)

26. hex() 十進制轉十六進制

print(hex(255)) ?# '0xff'

27. id() 獲取對象的唯一標識符

a = 10
print(id(a))

28. input() 獲取用戶輸入

name = input("請輸入你的名字: ")
print("你好, " + name)

29. int() 轉換為整數

print(int("123")) ?# 123

30. isinstance() 檢查對象類型

print(isinstance(123, int)) ?# True

31. issubclass() 檢查是否是子類

class A: pass
class B(A): pass
print(issubclass(B, A)) ?# True

32. iter() 獲取迭代器

lst = [1, 2, 3]
it = iter(lst)
print(next(it)) ?# 1

33. len() 獲取長度

print(len([1, 2, 3])) ?# 3

34. list() 創建列表

print(list("hello")) ?# ['h', 'e', 'l', 'l', 'o']

35. locals() 獲取局部變量

def func():a = 10print(locals())func()

36. map() 對序列中的每個元素進行操作

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared) ?# [1, 4, 9, 16]

37. max() 返回最大值

print(max([10, 20, 5])) ?# 20
print(max("python")) ?# 'y'

38. min() 返回最小值

print(min([10, 20, 5])) ?# 5
print(min("python")) ?# 'h'

39. next() 獲取迭代器的下一個元素

it = iter([10, 20, 30])
print(next(it)) ?# 10
print(next(it)) ?# 20

40. object() 創建一個新對象

obj = object()
print(obj) ?# <object object at 0x...>

41. oct() 十進制轉八進制

print(oct(10)) ?# '0o12'

42. open() 打開文件

with open("test.txt", "w") as f:f.write("Hello, Python!")

43. pow() 計算指數冪

print(pow(2, 3)) ?# 8
print(pow(2, 3, 5)) ?# (2^3) % 5 = 3

44. print() 打印輸出

print("Hello", "Python", sep="-") ?# Hello-Python

45. range() 生成范圍序列

print(list(range(1, 10, 2))) ?# [1, 3, 5, 7, 9]

46. repr() 返回對象的字符串表示

print(repr("Hello\nWorld")) ?# "'Hello\\nWorld'"

47. reversed() 反轉序列

print(list(reversed([1, 2, 3, 4]))) ?# [4, 3, 2, 1]

48. round() 四舍五入

print(round(3.14159, 2)) ?# 3.14

49. set() 創建集合

print(set([1, 2, 2, 3])) ?# {1, 2, 3}

50. setattr() 設置對象屬性

class Person:pass
p = Person()
setattr(p, "age", 25)
print(p.age) ?# 25

51. slice() 創建切片對象

lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s]) ?# [20, 30]

52. sorted() 排序

print(sorted([3, 1, 4, 2])) ?# [1, 2, 3, 4]
print(sorted("python")) ?# ['h', 'n', 'o', 'p', 't', 'y']

53. staticmethod() 定義靜態方法

class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4)) ?# 7

54. str() 轉換為字符串

print(str(123)) ?# '123'
print(str([1, 2, 3])) ?# '[1, 2, 3]'

55. sum() 計算總和

print(sum([1, 2, 3, 4])) ?# 10

56. super() 調用父類方法

class Parent:def greet(self):print("Hello from Parent")class Child(Parent):def greet(self):super().greet()print("Hello from Child")c = Child()
c.greet()

57. tuple() 創建元組

print(tuple([1, 2, 3])) ?# (1, 2, 3)

58. type() 獲取對象類型

print(type(123)) ?# <class 'int'>

59. vars() 獲取對象的 __dict__ 屬性

class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p)) ?# {'name': 'Alice', 'age': 25}

60. zip() 合并多個可迭代對象

names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages))) ?# [('Alice', 25), ('Bob', 30)]

61. __import__() 動態導入模塊

math_module = __import__("math")
print(math_module.sqrt(16)) ?# 4.0

62. delattr() 刪除對象的屬性

class Person:age = 25
delattr(Person, "age")
print(hasattr(Person, "age")) ?# False

63. exec() 執行字符串代碼

code = "x = 10\ny = 20\nprint(x + y)"
exec(code) ?# 30

64. memoryview() 創建內存視圖對象

b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0]) ?# 104

65. round() 取整

print(round(4.567, 2)) ?# 4.57

66. breakpoint() 設置調試斷點

x = 10
breakpoint() ?# 進入調試模式
print(x)

67. classmethod() 定義類方法

class Person:name = "Unknown"@classmethoddef set_name(cls, name):cls.name = namePerson.set_name("Alice")
print(Person.name) ?# Alice

68. compile() 編譯字符串為代碼對象

code = "print('Hello, World!')"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code) ?# Hello, World!

69. complex() 創建復數

c = complex(3, 4)
print(c) ?# (3+4j)

70. del 刪除對象

x = 10
del x
# print(x) ?# NameError: name 'x' is not defined

71. ellipsis 省略號對象

def func():...
print(func()) ?# None

72. float.fromhex() 將十六進制轉換為浮點數

print(float.fromhex('0x1.8p3')) ?# 12.0

73. format_map() 使用映射對象格式化字符串

class Person:age = 25
print(getattr(Person, "age")) ?# 25

74. getattr() 獲取對象屬性

class Person:age = 25
print(getattr(Person, "age")) ?# 25

75. is 判斷是否是同一個對象

a = [1, 2, 3]
b = a
print(a is b) ?# True

76. issubclass() 判斷是否是子類

class A: pass
class B(A): passprint(issubclass(B, A)) ?# True

77. iter() 創建迭代器

lst = [1, 2, 3]
it = iter(lst)
print(next(it)) ?# 1

78. len() 獲取長度

print(len([1, 2, 3])) ?# 3

79. memoryview() 創建內存視圖

b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0]) ?# 104

80. object() 創建基礎對象

obj = object()
print(obj)

81. print(*objects, sep, end, file, flush) 高級用法

print("Hello", "World", sep="-", end="!") ?# Hello-World!

82. property() 創建只讀屬性

class Person:def __init__(self, name):self._name = name@propertydef name(self):return self._namep = Person("Alice")
print(p.name) ?# Alice

83. repr() 返回字符串表示

print(repr("Hello\nWorld")) ?# 'Hello\nWorld'

84. round() 四舍五入

print(round(4.567, 2)) ?# 4.57

85. set() 創建集合

s = set([1, 2, 3, 3])
print(s) ?# {1, 2, 3}

86. setattr() 設置對象屬性

class Person:pass
p = Person()
setattr(p, "age", 30)
print(p.age) ?# 30

87. slice() 創建切片對象

lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s]) ?# [20, 30]

88. sorted() 排序

print(sorted([3, 1, 4, 2])) ?# [1, 2, 3, 4]

89. staticmethod() 定義靜態方法

class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4)) ?# 7

90. sum() 計算總和

print(sum([1, 2, 3, 4])) ?# 10

91. super() 調用父類方法

class Parent:def greet(self):print("Hello from Parent")
class Child(Parent):def greet(self):super().greet()print("Hello from Child")
c = Child()
c.greet()

92. tuple() 創建元組

print(tuple([1, 2, 3])) ?# (1, 2, 3)

93. type() 獲取對象類型

print(type(123)) ?# <class 'int'>

94. vars() 獲取對象屬性字典

class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p)) ?# {'name': 'Alice', 'age': 25}

95. zip() 壓縮多個可迭代對象

names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages))) ?# [('Alice', 25), ('Bob', 30)]

96. callable() 檢測對象是否可調用

def foo():pass
print(callable(foo)) ?# True

97. bin() 轉換為二進制

print(bin(10)) ?# '0b1010'

98. hex() 轉換為十六進制

print(hex(255)) ?# '0xff'

99. oct() 轉換為八進制

print(oct(8)) ?# '0o10'

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/71965.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/71965.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/71965.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python畢業設計選題:基于django+vue的疫情數據可視化分析系統

開發語言&#xff1a;Python框架&#xff1a;djangoPython版本&#xff1a;python3.7.7數據庫&#xff1a;mysql 5.7數據庫工具&#xff1a;Navicat11開發軟件&#xff1a;PyCharm 系統展示 管理員登錄 管理員功能界面 用戶管理 員工管理 疫情信息管理 檢測預約管理 檢測結果…

C#程序結構及基本組成說明

C# 程序的結構主要由以下幾個部分組成,以下是對其結構的詳細說明和示例: 1. 基本組成部分 命名空間 (Namespace) 用于組織代碼,避免命名沖突。通過 using 引入其他命名空間。 using System; // 引入 System 命名空間類 (Class) C# 是面向對象的語言,所有代碼必須定義在類或…

Python 編程題 第八節:字符串變形、壓縮字符串、三個數的最大乘積、判定字符是否唯一、IP地址轉換

字符串變形 swapcase()方法將字符串大小寫轉換&#xff1b;split()方法將字符串以括號內的符號分隔并以列表形式返回 sinput() ls.split(" ") ll[::-1] s"" for i in l:ai.swapcase()sas" " print(s[0:len(s)-1]) 壓縮字符串 很巧妙的方法 …

大語言模型學習--向量數據庫基礎知識

1.向量 向量是多維數據空間中的一個坐標點。 向量類型 圖像向量 文本向量 語音向量 Embedding 非結構化數據轉換為向量過程 通過深度學習訓練&#xff0c;將真實世界離散數據&#xff0c;投影到高維數據空間上&#xff0c;通過數據在空間中間的距離體現真實世界的相似度 V…

項目工坊 | Python驅動淘寶信息爬蟲

目錄 前言 1 完整代碼 2 代碼解讀 2.1 導入模塊 2.2 定義 TaoBao 類 2.3 search_infor_price_from_web 方法 2.3.1 獲取下載路徑 2.3.2 設置瀏覽器選項 2.3.3 反爬蟲處理 2.3.4 啟動瀏覽器 2.3.5 修改瀏覽器屬性 2.3.6 設置下載行為 2.3.7 打開淘寶登錄頁面 2.3.…

藍橋杯題型

藍橋杯 藍橋杯題型分類語法基礎藝術與籃球&#xff08;日期問題&#xff09;時間顯示&#xff08;時間問題&#xff09;跑步計劃&#xff08;日期問題&#xff09;偶串(字符&#xff09;最長子序列&#xff08;字符&#xff09;字母數&#xff08;進制轉換&#xff09;6個0&…

【C語言】文件操作篇

目錄 文件的基本概念文本文件和二進制文件的差異 文件指針FILE 結構體文件指針的初始化和賦值 文件打開與關閉常見操作文件的打開文件的關閉 常見問題打開文件時的路徑問題打開文件失敗的常見原因fclose 函數的重要性 文件讀寫操作常見操作字符讀寫字符串讀寫格式化讀寫二進制讀…

【leetcode hot 100 21】合并兩個有序鏈表

解法一&#xff1a;新建一個鏈表存放有序的合并鏈表。當list1和list2至少有一個非空時&#xff0c;返回非空的&#xff1b;否則找出兩個鏈表的最小值作為新鏈表的頭&#xff0c;然后依次比較兩鏈表&#xff0c;每次都先插入小的值。 /*** Definition for singly-linked list.*…

Ubuntu 24.04.2 安裝 PostgreSQL 16 、PostGIS 3

安裝 PostgreSQL 16 apt install postgresql-16passwd postgres&#xff0c;修改 postgres 用戶密碼su postgrespsql -U postgres, 以 postgres 的身份登錄數據庫alter user postgres with password abc123;\q 退出/etc/postgresql/16/main/postgresql.conf 可修改 #listen_ad…

Spring Boot框架總結(超級詳細)

前言 本篇文章包含Springboot配置文件解釋、熱部署、自動裝配原理源碼級剖析、內嵌tomcat源碼級剖析、緩存深入、多環境部署等等&#xff0c;如果能耐心看完&#xff0c;想必會有不少收獲。 一、Spring Boot基礎應用 Spring Boot特征 概念&#xff1a; 約定優于配置&#…

postgresql14編譯安裝腳本

#!/bin/bash####################################readme################################### #先上傳postgresql源碼包&#xff0c;再配置yum源&#xff0c;然后執行腳本 #備份官方yum源配置文件&#xff1a; #cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS…

AI開發利器:miniforge3無感平替Anaconda3

相信有和我遭遇一樣的同學吧&#xff0c;之前裝了anaconda用的挺好的&#xff08;可以參考AI開發利器&#xff1a;Anaconda&#xff09;&#xff0c;但是考慮到有可能收到軟件侵權的律師函的風險&#xff0c;還是果斷找個替代品把anaconda卸載掉。miniforge就是在這樣的背景下發…

Reactor中的Flux和Mono的區別

Reactor中的Flux和Mono的區別 在Reactor框架中&#xff0c;Flux 和 Mono 是兩個核心的類型&#xff0c;分別用于處理不同的數據流場景。理解它們之間的區別是掌握響應式編程的關鍵。 1. 基本概念 Flux: 表示一個異步、非阻塞的流&#xff0c;能夠發布零個或多個元素。它適用于…

AI-NAS:當存儲遇上智能,開啟數據管理新紀元

在數據爆炸的時代&#xff0c;NAS&#xff08;網絡附加存儲&#xff09;已成為個人和企業存儲海量數據的利器。然而&#xff0c;面對日益龐大的數據量&#xff0c;傳統的NAS系統在文件管理和搜索效率上逐漸力不從心。AI-NAS應運而生&#xff0c;它將NAS與人工智能&#xff08;A…

用 Vue 3.5 TypeScript 做了一個日期選擇器(改進版)

上一篇 已經實現了一個日期選擇器&#xff0c;只不過是模態窗的形式&#xff0c;這個版本改為文本框彈出&#xff0c;點擊空白處可關閉日歷 代碼也增加了不少 <template><div><!-- 添加文本框 --><div class"date-picker-input-wrapper">&l…

【09】單片機編程核心技巧:變量賦值,從定義到存儲的底層邏輯

【09】單片機編程核心技巧&#xff1a;變量賦值&#xff0c;從定義到存儲的底層邏輯 &#x1f31f; 核心概念 單片機變量的定義與賦值是程序設計的基礎&#xff0c;其本質是通過 RAM&#xff08;隨機存儲器&#xff09; 和 ROM&#xff08;只讀存儲器&#xff09; 的協作實現…

【爬蟲】開篇詞

一、網絡爬蟲概述 二、網絡爬蟲的應用場景 三、爬蟲的痛點 四、需要掌握哪些技術&#xff1f; 在這個信息爆炸的時代&#xff0c;如何高效地獲取和處理海量數據成為一項核心技能。無論是數據分析、商業情報、學術研究&#xff0c;還是人工智能訓練&#xff0c;網絡爬蟲&…

文字轉語音chat-tts-ui

去年已經使用過chattts了&#xff0c;但是昨晚想用的時候卻記怎么打開了&#xff0c;找了一下以前的筆記 MacOS 下源碼部署chat-tts-ui 配置好 python3.9-3.11 環境,安裝git &#xff0c;執行命令 brew install libsndfile git python3.10 繼續執行 brew install ffmpeg ? …

基于SpringBoot+Vue的瑜伽課體驗課預約系統【附源碼】

基于SpringBootVue的瑜伽課體驗課預約系統 一、系統技術說明二、運行說明三、系統的演示四、系統的核心代碼演示 一、系統技術說明 框架&#xff1a;SpringbootVue 數據庫&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09; 數據庫工具&#xff1a;Navicat11 開發軟…

sparkTTS window 安裝

SparkTTS 的簡介 Spark-TTS是一種基于SpardAudio團隊提出的 BiCodec 構建的新系統&#xff0c;BiCodec 是一種單流語音編解碼器&#xff0c;可將語音策略性地分解為兩種互補的標記類型&#xff1a;用于語言內容的低比特率語義標記和用于說話者特定屬性的固定長度全局標記。這種…