Python 基础笔记
1.String
01.在Python中,字符串前加上r(即原始字符串字面量)的作用是告诉解释器,字符串中的反斜杠\应该被视为普通字符,而不是转义字符。这意味着字符串中的所有反斜杠都会被保留,不会被解释为转义字符。
# 普通字符串 path = "C:\\Users\\Username\\Documents" # 原始字符串 path = r"C:\Users\Username\Documents"
02.用三个单引号或者三个双引号包含起来多行文本
message = """first line 001 second line 002 third 003 """
03.在Python中,字符串前加上f(即格式化字符串字面量)的作用是允许你在字符串中嵌入表达式,这些表达式会被计算并替换为相应的值。这种字符串格式化方式从Python 3.6开始引入,提供了简洁且直观的方式来创建动态字符串
x = 10 y = 20 result = f"The sum of {x} and {y} is {x + y}." print(result) # 输出: The sum of 10 and 20 is 30.
Python中常见的类型转换函数
# int() 示例 str_num = "456" int_num = int(str_num) print(int_num) # 456 # float() 示例 str_float = "78.9" float_num = float(str_float) print(float_num) # 78.9 # str() 示例 num = 100 str_num = str(num) print(str_num) # "100" # bool() 示例 empty_list = [] bool_empty_list = bool(empty_list) print(bool_empty_list) # False # list() 示例 tuple_example = (1, 2, 3) list_from_tuple = list(tuple_example) print(list_from_tuple) # [1, 2, 3] # tuple() 示例 list_example = [4, 5, 6] tuple_from_list = tuple(list_example) print(tuple_from_list) # (4, 5, 6) # set() 示例 list_with_duplicates = [1, 2, 2, 3] set_from_list = set(list_with_duplicates) print(set_from_list) # {1, 2, 3} # dict() 示例 list_of_tuples = [('a', 1), ('b', 2)] dict_from_list_of_tuples = dict(list_of_tuples) print(dict_from_list_of_tuples) # {'a': 1, 'b': 2} # complex() 示例 str_complex = "5+6j" complex_num = complex(str_complex) print(complex_num) # (5+6j)
三元条件表达式
# value_if_true if condition else value_if_false age = 18 status = "Adult" if age >= 18 else "Minor" print(status) # 输出: Adult
Python 循环常用range函数: Python中的range()函数用于生成一个整数序列,通常用于循环中。range()函数有三种不同的使用方式:
range(stop):
生成从0到stop-1的整数序列。
range(start, stop):
生成从start到stop-1的整数序列。
range(start, stop, step):
生成从start到stop-1的整数序列,步长为step。
其他常见用法:将range()转换为列表
# 将range对象转换为列表 numbers = list(range(5)) print(numbers) # 输出: [0, 1, 2, 3, 4]
# 生成从10到1的整数序列,步长为-1 for i in range(10, 0, -1): print(i)
函数
在Python中,可以使用类型注解(type hints)来指定函数参数和返回值的类型。类型注解是从Python 3.5开始引入的,虽然它们不是强制性的,但可以提高代码的可读性和可维护性,并且有助于静态类型检查工具(如mypy)进行类型检查。
注意事项
类型注解不是强制性的:类型注解不会在运行时强制执行类型检查,它们主要用于静态类型检查工具和代码阅读者。
使用静态类型检查工具:可以使用mypy等工具来检查代码中的类型错误。
pip install mypy mypy your_script.py
# 示例4: 带返回值的函数 def add(a: int, b: int) -> int: return a + b result = add(3, 5) print(result) # 输出: 8 # 示例6: 使用**kwargs接收任意数量的关键字参数 def print_info(**kwargs: str) -> None: for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age="30", city="New York") # 输出: # name: Alice # age: 30 # city: New York复杂类型:
对于更复杂的类型,可以使用typing模块中的类型。
from typing import List, Dict def process_data(data: List[Dict[str, int]]) -> None: for item in data: print(item) data = [{"a": 1}, {"b": 2}] process_data(data)
Lambda表达式
Lambda表达式(匿名函数)是Python中一种简洁的函数定义方式,适用于需要简单函数的场合。Lambda表达式可以接受任意数量的参数,但只能有一个表达式,其结果就是返回值。Lambda表达式的语法如下:
lambda 参数1, 参数2, ... : 表达式
# 示例1: 基本Lambda表达式,计算两个数的和 add = lambda x, y: x + y result = add(3, 5) print(result) # 输出: 8 # 示例2: 单个参数的Lambda表达式,计算一个数的平方 square = lambda x: x ** 2 result = square(4) print(result) # 输出: 16 # 示例3: 无参数的Lambda表达式 greet = lambda: "Hello, World!" print(greet()) # 输出: Hello, World! # 示例4: 多个参数的Lambda表达式,计算三个数的乘积 multiply = lambda x, y, z: x * y * z result = multiply(2, 3, 4) print(result) # 输出: 24 # 示例5: 使用Lambda表达式作为函数参数 # 使用map()函数对列表中的每个元素进行平方运算 numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x ** 2, numbers)) print(squared_numbers) # 输出: [1, 4, 9, 16, 25] # 使用filter()函数过滤出列表中的偶数 numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # 输出: [2, 4, 6] # 使用sorted()函数按年龄排序 students = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 20}, {"name": "Charlie", "age": 30} ] sorted_students = sorted(students, key=lambda student: student["age"]) print(sorted_students) # 输出: # [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}] # 示例6: 嵌套Lambda表达式 add_and_multiply = lambda x, y: (lambda a, b: a + b)(x, y) * 2 result = add_and_multiply(3, 5) print(result) # 输出: 16
List 常用方法示例
# 示例1: 创建列表 empty_list = [] fruits = ["apple", "banana", "cherry"] numbers = list(range(5)) # 使用list()函数创建 print(empty_list) # 输出: [] print(fruits) # 输出: ['apple', 'banana', 'cherry'] print(numbers) # 输出: [0, 1, 2, 3, 4] # 示例2: 访问列表元素 first_fruit = fruits[0] # 访问第一个元素 last_fruit = fruits[-1] # 访问最后一个元素 first_three = fruits[:3] # 获取前三个元素 middle_two = fruits[1:4] # 获取从第二个到第四个元素 last_one = fruits[-1:] # 获取最后一个元素 print(first_fruit) # 输出: apple print(last_fruit) # 输出: cherry print(first_three) # 输出: ['apple', 'banana', 'cherry'] print(middle_two) # 输出: ['banana', 'cherry', 'date'] print(last_one) # 输出: ['elderberry'] # 示例3: 修改列表元素 fruits[1] = "blueberry" fruits[:3] = ["apricot", "blueberry", "cantaloupe"] # 修改前三个元素 print(fruits) # 输出: ['apricot', 'blueberry', 'cantaloupe', 'date', 'elderberry'] # 示例4: 添加元素 fruits.append("date") # 在末尾添加一个元素 fruits.insert(1, "banana") # 在索引1处插入一个元素 more_fruits = ["fig", "grape"] fruits.extend(more_fruits) # 将另一个列表的元素添加到末尾 print(fruits) # 输出: ['apricot', 'banana', 'blueberry', 'cantaloupe', 'date', 'elderberry', 'fig', 'grape'] # 示例5: 删除元素 fruits.remove("banana") # 删除第一个匹配的元素 last_fruit = fruits.pop() # 删除并返回最后一个元素 first_fruit = fruits.pop(0) # 删除并返回指定索引的元素 del fruits[1] # 删除指定索引的元素 print(fruits) # 输出: ['apricot', 'cantaloupe', 'date', 'elderberry', 'fig', 'grape'] # del fruits # 删除整个列表 # print(fruits) # 这会引发NameError,因为fruits已被删除 # 示例6: 排序列表 numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] numbers.sort() # 升序排序 sorted_numbers = sorted(numbers) # 升序排序,返回新列表 numbers.sort(reverse=True) # 降序排序 sorted_numbers_desc = sorted(numbers, reverse=True) # 降序排序,返回新列表 print(numbers) # 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] print(sorted_numbers) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] print(numbers) # 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] print(sorted_numbers_desc) # 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] # 示例7: 遍历列表 for fruit in fruits: print(fruit) for index, fruit in enumerate(fruits): # 遍历列表并获取索引和元素 print(f"Index {index}: {fruit}") # 输出: # Index 0: apricot # Index 1: cantaloupe... # 示例8: 列表推导式 是一种简洁的方式来创建列表。 squares = [x**2 for x in range(1, 11)] # 创建一个包含1到10的平方数的列表 even_squares = [x**2 for x in range(1, 11) if x % 2 == 0] # 使用条件过滤 print(squares) # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print(even_squares) # 输出: [4, 16, 36, 64, 100] # 示例9: 其他常用方法 length = len(fruits) # 获取列表的长度 is_present = "banana" in fruits # 检查元素是否在列表中 count_of_2 = numbers.count(2) # 计算元素出现的次数 index_of_apricot = fruits.index("apricot") # 获取元素的索引 numbers.reverse() # 反转列表 print(length) # 输出: 6 print(is_present) # 输出: False print(count_of_2) # 输出: 3 print(index_of_apricot) # 输出: 1 print(numbers) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
List 自定义排序
# 示例: 使用 list.sort() 实现自定义排序 students = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 20}, {"name": "Charlie", "age": 30} ] students.sort(key=lambda student: student["age"]) print(students) # 输出: [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}] # 指定自定义排序 按哪个字段进行升降序排序 def student_sort_key(student): return student["age"] students.sort(key=student_sort_key, reverse=True) print(students) # 输出: [{'name': 'Charlie', 'age': 30}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}]
List 循环
fruits = ["apple", "banana", "cherry"] # 示例2: 使用 enumerate() 函数 for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}") # 输出: # Index 0: apple # Index 1: banana # Index 2: cherry # 示例4: 列表推导式 numbers = [1, 2, 3, 4, 5] squares = [x**2 for x in numbers] print(squares) # 输出: [1, 4, 9, 16, 25] # 示例7: 使用 zip() 函数 names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old.") # 输出: # Alice is 25 years old. # Bob is 30 years old. # Charlie is 35 years old. # 示例8 创建一个迭代器 iter 函数 fruit_iterator = iter(fruits) # 使用 for 循环遍历迭代器 for fruit in fruit_iterator: print(fruit) # 输出: # apple # banana # cherry
Tuple 在Python中,元组(Tuple)是一种有序且不可变的数据结构。元组可以包含任意类型的元素,并且一旦创建就不能修改其内容。
注意:default_tuple=1,2,3 只有逗号没有括号的表达式实质也是一个tuple,常见于函数返回值直接 return x,y,z 时,实际是函数返回了一个包含xyz的 tuple (x,y,z)
# 示例1: 创建元组 empty_tuple = () fruits = ("apple", "banana", "cherry") numbers = tuple(range(5)) single_element_tuple = (42,) # 创建一个包含单个元素的元组,注意逗号 print(empty_tuple) # 输出: () print(fruits) # 输出: ('apple', 'banana', 'cherry') print(numbers) # 输出: (0, 1, 2, 3, 4) print(single_element_tuple) # 输出: (42,) # 示例3: 解包元组 first, second, third = fruits print(first) # 输出: apple print(second) # 输出: banana print(third) # 输出: cherry # 示例4: 连接元组 tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) combined_tuple = tuple1 + tuple2 print(combined_tuple) # 输出: (1, 2, 3, 4, 5, 6) # 示例5: 重复元组 repeated_tuple = tuple1 * 3 print(repeated_tuple) # 输出: (1, 2, 3, 1, 2, 3, 1, 2, 3) # 示例6: 元组不可变性 # fruits[1] = "blueberry" # 这会引发TypeError fruits = ("apple", "blueberry", "cherry") # 但可以重新赋值整个元组 print(fruits) # 输出: ('apple', 'blueberry', 'cherry')
List Tuple Dict 等解包:解包(Unpacking)是一种将可迭代对象(如列表、元组、字典等)中的元素分配给多个变量的操作。解包可以简化代码并提高可读性。
# 示例1: 元组解包 fruits = ("apple", "banana", "cherry") first, second, third = fruits print(first) # 输出: apple print(second) # 输出: banana print(third) # 输出: cherry # 示例2: 使用星号 * 解包元组,*表明把剩余的元素打包成一个元组 fruits = ("apple", "banana", "cherry", "date", "elderberry") first, *middle, last = fruits print(first) # 输出: apple print(middle) # 输出: ['banana', 'cherry', 'date'] print(last) # 输出: elderberry # 示例5: 解包字典的键 student = {"name": "Alice", "age": 25, "city": "New York"} name, age, city = student.keys() print(name) # 输出: name print(age) # 输出: age print(city) # 输出: city # 示例6: 解包字典的值 student = {"name": "Alice", "age": 25, "city": "New York"} name, age, city = student.values() print(name) # 输出: Alice print(age) # 输出: 25 print(city) # 输出: New York # 示例7: 解包字典的键值对 student = {"name": "Alice", "age": 25, "city": "New York"} for key, value in student.items(): print(f"{key}: {value}") # 输出: # name: Alice # age: 25 # city: New York # 示例8: 位置参数解包 def add(a, b, c): return a + b + c numbers = (1, 2, 3) result = add(*numbers) # 对应函数调用的位置参数理解 print(result) # 输出: 6 # 示例9: 关键字参数解包 def greet(name, age, city): return f"Name: {name}, Age: {age}, City: {city}" student = {"name": "Alice", "age": 25, "city": "New York"} result = greet(**student) # 对应函数调用的关键字参数理解 print(result) # 输出: Name: Alice, Age: 25, City: New York
Python 打包exe
pip install pyinstaller pyinstaller --name=my_program -F --noconsole your_script.py
示例:pyinstaller --onefile --noconsole .\main.py
基本命令:最简单的打包命令是 pyinstaller your_script.py,这会生成一个默认名称的可执行文件。
指定输出文件名:
使用 --name 参数可以自定义生成的可执行文件的名称。
示例:pyinstaller --name=my_program your_script.py,这将生成名为 my_program 的可执行文件。
单文件模式:
如果你希望将所有依赖打包进一个单独的可执行文件中,可以使用 -F 或 --onefile 参数。
示例:pyinstaller --name=my_program -F your_script.py。
--noconsole:如果你不希望运行时显示命令行窗口(适用于GUI程序),可以添加此参数
Python 程序弹常见消息框
tkinter 是Python的标准GUI库,可以用来创建简单的对话框,,无需额外安装
import tkinter as tk from tkinter import messagebox def show_success_dialog(): root = tk.Tk() root.withdraw() # 隐藏主窗口 messagebox.showinfo("成功", "程序执行成功!") root.destroy() if __name__ == "__main__": # 你的程序逻辑 print("执行一些操作...") # 弹出成功对话框 show_success_dialog()
map 函数:map 函数在 Python 中用于将一个函数应用到一个可迭代对象(如列表、元组等)的每个元素上,并返回一个迭代器。
# 示例数字列表 numbers = [1, 2, 3, 4, 5] # 使用 map 函数和 lambda 函数将每个数字平方 squared_numbers = map(lambda x: x**2, numbers) # 将结果转换为列表并打印 [1, 4, 9, 16, 25] squared_numbers_list = list(squared_numbers) print(squared_numbers_list)
filter 函数:filter 函数在 Python 中用于过滤一个可迭代对象(如列表、元组等),只保留满足特定条件的元素.并返回一个迭代器。 用法和map函数一致.
reduce 函数:reduce 函数在 Python 中用于对一个可迭代对象(如列表、元组等)进行累积操作。reduce 函数需要一个二元函数(即接受两个参数的函数)和一个可迭代对象,并将该函数累积地应用到可迭代对象的元素上。
reduce 函数位于 functools 模块中,因此在使用之前需要先导入该模块。
from functools import reduce # 示例数字列表 numbers = [1, 2, 3, 4, 5] # 使用 reduce 函数和 lambda 函数计算累加和 sum_of_numbers = reduce(lambda x, y: x + y, numbers) print(sum_of_numbers)
列表解析:对一个列表进行操作并生成一个新列表的过程 表达式 [输出表达式 for 元素 in 列表]
带条件的列表解析:[输出表达式 for 元素 in 列表 if 条件语句]
字典常用操作:
# 创建一个空字典 empty_dict = {} # 使用字面量创建字典 person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # 使用 dict 构造函数创建字典 person = dict(name='Alice', age=25, city='New York') # 通过键访问值 name = person['name'] # 输出: Alice # 使用 get 方法访问值(避免键不存在时报错) age = person.get('age') # 输出: 25 height = person.get('height', 'Unknown') # 输出: Unknown # 添加新的键值对 person['job'] = 'Engineer' # 修改现有的键值对 person['age'] = 26 # 使用 del 关键字删除键值对 del person['city'] # 使用 pop 方法删除键值对并返回值 age = person.pop('age') # 输出: 26 # 获取所有键 keys = person.keys() # 输出: dict_keys(['name', 'job']) # 获取所有值 values = person.values() # 输出: dict_values(['Alice', 'Engineer']) # 获取所有键值对 items = person.items() # 输出: dict_items([('name', 'Alice'), ('job', 'Engineer')]) # 遍历键 for key in person: print(key) # 遍历值 for value in person.values(): print(value) # 遍历键值对 for key, value in person.items(): print(f"{key}: {value}") # 清空字典 person.clear() # 使用 update 方法合并字典 person.update({'age': 27, 'city': 'San Francisco'}) # 使用字典解包合并字典(Python 3.5+) new_person = {**person, 'job': 'Data Scientist'} # 示例字典 dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} # 使用字典解包合并字典 merged_dict = {**dict1, **dict2} # 使用 zip 函数从两个列表创建字典 keys = ['name', 'age', 'city'] values = ['Bob', 30, 'Los Angeles'] person = dict(zip(keys, values)) # 字典解析 person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # 使用字典解析创建字典,并添加条件和表达式 transformed_dict = {key.upper(): value for key, value in person.items() if isinstance(value, str)} print(transformed_dict) #输出{'NAME': 'Alice', 'CITY': 'New York'}
Set 集合:集合是一种无序且不重复的元素集合。
# 创建集合 fruits = {'apple', 'banana', 'cherry'} vegetables = {'carrot', 'lettuce', 'spinach'} # 创建一个空集合 empty_set = set() # 使用 set 构造函数创建集合 vegetables = set(['carrot', 'lettuce', 'spinach']) # 添加元素 fruits.add('orange') fruits.update(['grape', 'melon']) # 删除元素 fruits.remove('banana') # 使用 remove 方法删除元素(如果元素不存在会引发 KeyError) fruits.discard('grape') # 使用 discard 方法删除元素(如果元素不存在不会引发错误) popped_element = fruits.pop() # 使用 pop 方法随机删除并返回一个元素 # 检查元素是否存在 if 'apple' in fruits: print("Apple is in the set") # 获取集合长度 length = len(fruits) print(f"Length of fruits set: {length}") # 集合操作 set1 = {1, 2, 3} set2 = {3, 4, 5} # 并集 union_set = set1.union(set2) print(f"Union: {union_set}") # 交集 intersection_set = set1.intersection(set2) print(f"Intersection: {intersection_set}") # 差集 difference_set = set1.difference(set2) print(f"Difference: {difference_set}") # 对称差集 symmetric_difference_set = set1.symmetric_difference(set2) print(f"Symmetric Difference: {symmetric_difference_set}") # 子集和超集 subset = {1, 2} is_subset = subset.issubset(set1) is_superset = set1.issuperset(subset) print(f"Is subset: {is_subset}") print(f"Is superset: {is_superset}") # 冻结集合 frozen_fruits = frozenset(['apple', 'banana', 'cherry']) print(f"Frozen set: {frozen_fruits}")
Python __name__ 变量
在 Python 中,__name__ 是一个特殊的内置变量,用于表示当前模块的名称。它的值取决于模块是如何被使用的。以下是 __name__ 变量的详细说明和使用示例:
基本说明
模块作为主程序运行:当一个 Python 文件被直接执行时,__name__ 的值会被设置为 '__main__'。
模块被导入:当一个 Python 文件被作为模块导入到另一个文件中时,__name__ 的值会被设置为该模块的名称(即文件名,不带 .py 扩展名)。
使用场景
通常,__name__ 变量用于区分模块是被直接运行还是被导入。这在编写可重用的模块时非常有用,因为它允许你在模块中包含测试代码或示例代码,这些代码只有在模块被直接运行时才会执行。
Python __init__.py 文件
标识包:__init__.py 文件将目录标识为一个包。
初始化包:可以在 __init__.py 文件中包含初始化代码。
控制导入:使用 __all__ 变量控制 from package import * 时导入的内容。
通过合理使用 __init__.py 文件,可以更好地组织和管理 Python 代码,使其更具模块化和可维护性。
Python 生成requirements.txt 引用包文件
pip list 查看当前项目所安装的包
#pip freeze 命令会列出当前环境中所有已安装的包及其版本 pip freeze #重定向到 requirements.txt 文件 pip freeze > requirements.txt #使用 pip install -r requirements.txt 命令安装所有列出的包 pip install -r requirements.txt

浙公网安备 33010602011771号