Python 编程常用实例:高级专家篇
字符串转换为整数列表
string_numbers = "1 2 3 4 5"numbers = list(map(int, string_numbers.split()))print(numbers)说明:使用 map() 函数将字符串转换为整数列表。
条件语句
x = 7if x > 5:print("x is greater than 5")else:print("x is less than or equal to 5")说明:使用条件语句控制程序流程。
遍历列表
fruits = ["apple", "banana", "cherry"]for fruit in fruits:print(fruit)说明:使用 for 循环遍历列表。
while 循环
count = 0while count < 5:print(count)count += 1说明:使用 while 循环按条件重复执行代码。
获取列表索引和值
for index, value in enumerate(["apple", "banana", "cherry"]):print(index, value)说明:使用 enumerate() 获取列表的索引和值。
列表切片
fruits = ["apple", "banana", "cherry", "date", "elderberry"]print(fruits[1:4])说明:使用列表切片访问子集。
字符串格式化
name = "John"age = 30print(f"My name is {name} and I am {age} years old.")说明:使用 f-string 进行字符串格式化。
异常处理
try:result = 10 / 0except ZeroDivisionError:print("Cannot divide by zero")说明:捕获和处理异常。
类定义
class Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):print(f"Hello, my name is {self.name} and I am {self.age} years old.")person = Person("John", 30)person.greet()说明:定义和使用类。
集合并集
fruits_set = {"apple", "banana", "cherry"}veggies_set = {"carrot", "broccoli", "banana"}print(fruits_set | veggies_set)说明:使用集合操作进行并集运算。
创建字典
person_dict = {"name": "John", "age": 30, "city": "New York"}print(person_dict)说明:创建和使用字典。
访问字典值
person_dict = {"name": "John", "age": 30, "city": "New York"}print(person_dict["name"])说明:通过键访问字典中的值。
删除字典元素
person_dict = {"name": "John", "age": 30, "city": "New York"}del person_dict["age"]print(person_dict)说明:在字典中删除元素。
生成器函数
def countdown(n):while n > 0:yield nn -= 1for i in countdown(5):print(i)说明:使用生成器函数创建迭代器。
并行迭代多个列表
names = ["Alice", "Bob", "Charlie"]ages = [25, 30, 35]for name, age in zip(names, ages):print(name, age)说明:使用 zip() 并行迭代多个列表。
文件读写
with open('output.txt', 'w') as file:file.write("Hello, World!")with open('output.txt', 'r') as file:content = file.read()print(content)说明:使用 with 语句进行文件的读写操作。
THE END






