359 字
1 分鐘
人工智能Python复习(含代码版本)
人工智能Python复习(含代码版本)
第二章 Python序列
-
列表操作:
- 创建列表:
# 使用方括号a = [1, 2, 3, 4, 5]# 使用list()函数b = list((1, 2, 3, 4, 5))# 列表推导式c = [x * 2 for x in a]
- 增删改查:
a.append(6) # 添加元素a.extend([7, 8]) # 扩展列表a.insert(0, 0) # 在索引0处插入元素a.pop() # 删除并返回最后一个元素a.remove(3) # 删除指定元素del a[0] # 删除索引0处的元素
- 切片操作:
b = a[1:4] # 获取索引1到3的元素c = a[::2] # 获取每隔一个元素
- 排序:
a.sort() # 原地排序b = sorted(a) # 返回新列表并排序
- 成员判断:
if 5 in a:print("5 is in the list")if 6 not in a:print("6 is not in the list")
- 创建列表:
-
元组:
- 创建元组:
# 使用圆括号t = (1, 2, 3, 4, 5)# 使用tuple()函数u = tuple([1, 2, 3, 4, 5])
- 创建元组:
-
字典:
- 创建字典:
# 使用花括号d = {'a': 1, 'b': 2, 'c': 3}# 使用dict()函数e = dict(a=1, b=2, c=3)# 使用fromkeys()方法f = dict.fromkeys(['a', 'b', 'c'], 0)
- 操作字典:
value = d.get('a') # 获取键'a'的值d.update({'d': 4}) # 更新字典removed_value = d.pop('b') # 删除并返回键'b'的值keys = d.keys() # 获取所有键values = d.values() # 获取所有值items = d.items() # 获取所有键值对
- 创建字典:
-
集合:
- 创建集合:
# 使用花括号s = {1, 2, 3, 4, 5}# 使用set()函数t = set([1, 2, 3, 4, 5])
- 集合运算:
s1 = {1, 2, 3}s2 = {3, 4, 5}union = s1 | s2 # 并集intersection = s1 & s2 # 交集difference = s1 - s2 # 差集symmetric_difference = s1 ^ s2 # 对称差集
- 创建集合:
第三章 选择与循环
-
条件表达式:
x = 10if x > 0:print("x is positive")elif x == 0:print("x is zero")else:print("x is negative") -
循环结构:
- for循环:
for i in range(5):print(i)else:print("Loop completed")
- while循环:
i = 0while i < 5:print(i)i += 1else:print("Loop completed")
- 循环控制:
for i in range(10):if i == 5:break # 跳出循环if i % 2 == 0:continue # 跳过偶数print(i)
- for循环:
第四章 字符串与正则表达式
-
字符串操作:
- 格式化:
name = "Alice"age = 30message = f"Hello, {name}. You are {age} years old."print(message)
- 常用方法:
s = "Hello, World!"split_s = s.split(", ") # 按逗号和空格分割join_s = ", ".join(split_s) # 用逗号和空格连接replace_s = s.replace("World", "Python") # 替换字符串find_index = s.find("World") # 查找子字符串的索引
- 格式化:
-
正则表达式:
import retext = "The rain in Spain"# 查找所有匹配的子字符串findall_result = re.findall(r"\bS\w+", text)print(findall_result) # 输出: ['Spain']# 查找第一个匹配的子字符串search_result = re.search(r"\bS\w+", text)print(search_result.group()) # 输出: Spain# 匹配整个字符串match_result = re.match(r"\bT\w+", text)if match_result:print(match_result.group()) # 输出: The# 替换子字符串sub_result = re.sub(r"\bS\w+", "Country", text)print(sub_result) # 输出: The rain in Country# 分割字符串split_result = re.split(r"\s+", text)print(split_result) # 输出: ['The', 'rain', 'in', 'Spain']
第五章 函数的设计和使用
-
函数定义与参数:
- 位置参数、默认值参数、关键字参数:
def greet(name, greeting="Hello"):print(f"{greeting}, {name}!")greet("Alice") # 输出: Hello, Alice!greet("Bob", greeting="Hi") # 输出: Hi, Bob!
- 可变长度参数:
def sum_all(*args):return sum(args)print(sum_all(1, 2, 3, 4, 5)) # 输出: 15
- 参数解包:
def print_args(a, b, c):print(a, b, c)args = (1, 2, 3)print_args(*args) # 输出: 1 2 3kwargs = {'a': 1, 'b': 2, 'c': 3}print_args(**kwargs) # 输出: 1 2 3
- 位置参数、默认值参数、关键字参数:
-
作用域:
x = 10 # 全局变量def modify_x():global xx += 5modify_x()print(x) # 输出: 15 -
lambda表达式:
add_one = lambda x: x + 1print(add_one(5)) # 输出: 6
第六章 面向对象程序设计
-
类与对象:
class Animal:def __init__(self, name):self.name = namedef speak(self):print(f"{self.name} makes a sound")class Dog(Animal):def __init__(self, name, breed):super().__init__(name)self.breed = breeddef speak(self):print(f"{self.name} barks")dog = Dog("Buddy", "Golden Retriever")dog.speak() # 输出: Buddy barks -
成员与访问控制:
class MyClass:def __init__(self):self.public_var = 10self._protected_var = 20self.__private_var = 30 # 私有变量@propertydef private_var(self):return self.__private_varobj = MyClass()print(obj.public_var) # 输出: 10print(obj._protected_var) # 输出: 20print(obj.private_var) # 输出: 30(通过property访问) -
方法类型:
class MyClass:class_var = "I am a class variable"def instance_method(self):print(f"Instance method: {self.class_var}")@classmethoddef class_method(cls):print(f"Class method: {cls.class_var}")@staticmethoddef static_method():print("Static method")obj = MyClass()obj.instance_method() # 输出: Instance method: I am a class variableMyClass.class_method() # 输出: Class method: I am a class variableMyClass.static_method() # 输出: Static method -
继承与多态:
class Animal:def speak(self):print("Some generic sound")class Dog(Animal):def speak(self):super().speak() # 调用父类方法print("Woof!")class Cat(Animal):def speak(self):super().speak() # 调用父类方法print("Meow!")def animal_sound(animal):animal.speak()dog = Dog()cat = Cat()animal_sound(dog) # 输出: Some generic sound# Woof!animal_sound(cat) # 输出: Some generic sound# Meow!
第七章 文件操作
- 文件操作:
- 打开模式:
with open('example.txt', 'w') as f:f.write("Hello, World!")with open('example.txt', 'r') as f:content = f.read()print(content) # 输出: Hello, World!
- 读写方法:
with open('example.txt', 'w') as f:f.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])with open('example.txt', 'r') as f:lines = f.readlines()print(lines) # 输出: ['Line 1\n', 'Line 2\n', 'Line 3\n']
- xxxxxxxxxx import retext = “Call me at 123-456-7890 or 987.654.3210”pattern = r”\b\d{3}[-.]\d{3}[-.]\d{4}\b”matches = re.findall(pattern, text)print(matches) # 输出: [‘123-456-7890’, ‘987.654.3210’]python
with open('example.txt', 'r+') as f:print(f.read(5)) # 输出: Line 1f.seek(0) # 移动到文件开头print(f.read(5)) # 输出: Line 1
- 打开模式:
第八章 异常处理结构与程序调试
- 异常处理:
- try-except:
try:result = 10 / 0except ZeroDivisionError as e:print(f"Error: {e}")
- try-except-else:
try:result = 10 / 2except ZeroDivisionError as e:print(f"Error: {e}")else:print(f"Result is {result}") # 输出: Result is 5.0
- try-finally:
try:result = 10 / 0except ZeroDivisionError as e:print(f"Error: {e}")finally:print("This will always execute")
- try-except:
第九章 GUI编程
- tkinter基础:
import tkinter as tkdef on_button_click():print("Button was clicked!")root = tk.Tk()root.title("Tkinter Example")label = tk.Label(root, text="Hello, World!")label.pack()button = tk.Button(root, text="Click Me", command=on_button_click)button.pack()entry = tk.Entry(root)entry.pack()root.mainloop()
第十章 网络程序设计
- socket编程:
- 服务器端:
import socketserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server_socket.bind(('localhost', 8080))server_socket.listen(5)print("Server is listening on port 8080")while True:client_socket, addr = server_socket.accept()print(f"Connection from {addr} has been established")client_socket.send(b"Welcome to the server!")client_socket.close()
- 客户端:
import socketclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client_socket.connect(('localhost', 8080))message = client_socket.recv(1024)print(message.decode()) # 输出: Welcome to the server!client_socket.close()
- 服务器端:
第十三章 多线程与多进程编程
-
多线程:
import threadingdef print_numbers():for i in range(5):print(i)def print_letters():for letter in 'abcde':print(letter)thread1 = threading.Thread(target=print_numbers)thread2 = threading.Thread(target=print_letters)thread1.start()thread2.start()thread1.join()thread2.join() -
多进程:
from multiprocessing import Process, Queuedef worker(q):q.put("Hello from the worker process")q = Queue()p = Process(target=worker, args=(q,))p.start()message = q.get()print(message) # 输出: Hello from the worker processp.join()
分享
如果這篇文章對你有幫助,歡迎分享給更多人!
人工智能Python复习(含代码版本)
https://lemusakuya.com/posts/study-notes/python-basics/人工智能python复习含代码版本/ 部分資訊可能已經過時
相關文章 智能推薦
1
人工神经网络完全学习手册
Neural Networks 《神经网络》学习总览与学习路线
2
恶意代码分析与数字取证
Cybersecurity 《网络安全》学习笔记:恶意代码分析与数字取证
3
AD Rush
Android Development 《Android Development》学习笔记:AD Rush
4
Chapt5
Digital Image Processing 《Digital Image Processing》学习笔记:Chapt5
5
Chapt6
Digital Image Processing 《Digital Image Processing》学习笔记:Chapt6





















