1. 字符串
str1 = "Hello"
str2 = " World"
print(str1 + str2) # 输出:HelloWorld
1.1 字符替换
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) # 输出:Hello, Python!
1.2 字符串方法 - 大小写转换
text = "hello world"
upper_text = text.upper()
lower_text = text.lower()
print(upper_text) # 输出:HELLO WORLD
print(lower_text) # 输出:hello world
1.3 字符串格式化 - 使用format方法
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # 输出:My name is Alice and I am 30 years old.
1.4 字符串格式化 - f-string
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 输出:My name is Alice and I am 30 years old.
2. 列表
my_list = [1, 2, 3, 4, 5]
print(my_list)
2.1 访问列表
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 输出第一个元素
2.2 修改列表
my_list = [1, 2, 3, 4, 5]
my_list[0] = 10
print(my_list)
2.3 追加元素
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list)
2.3 列表排序
numbers = [5, 1, 9, 3, 7]
numbers.sort()
print(numbers) # 输出:[1, 3, 5, 7, 9]
2.4 列表反转
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # 输出:[5, 4, 3, 2, 1]
3. 元组
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
3.1 访问元组
my_tuple = (1, 2, 3, 4, 5)
# 访问第一个元素
first_element = my_tuple[0]
print(first_element) # 输出:1
# 访问最后一个元素
last_element = my_tuple[-1]
print(last_element) # 输出:5
3.2 元组切片
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# 切片获取部分元素
sub_tuple = my_tuple[2:5]
print(sub_tuple) # 输出:(3, 4, 5)
3.3 元组不可变性
my_tuple = (1, 2, 3)
# 尝试修改元组元素,这会抛出异常
# my_tuple[0] = 10 # 这行会引发TypeError
# 正确的方式是创建新的元组
new_tuple = (10,) + my_tuple[1:]
print(new_tuple) # 输出:(10, 2, 3)
3.4 元组与列表的转换
# 将列表转换为元组
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # 输出:(1, 2, 3)
# 将元组转换为列表
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # 输出:[1, 2, 3]
3.5 元组作为字典的键
# 元组可以作为字典的键,因为元组是不可变的
my_dict = {(1, 2): "one-two", (3, 4): "three-four"}
print(my_dict[(1, 2)]) # 输出:"one-two"
3.6 元组解包
# 解包元组到变量中
a, b, c = (1, 2, 3)
print(a) # 输出:1
print(b) # 输出:2
print(c) # 输出:3
# 解包带有星号的元组
first, *rest = (1, 2, 3, 4, 5)
print(first) # 输出:1
print(rest) # 输出:[2, 3, 4, 5]
4. 字典
my_dict = {"name": "Alice", "age": 30}
print(my_dict["name"])
4.1 字典更新
my_dict = {"name": "Alice", "age": 30}
my_dict["age"] = 31print(my_dict)
4.2 字典的get方法
my_dict = {'a': 1,'b': 2}
value = my_dict.get('a')
print(value) # 输出:1
value = my_dict.get('c', 'Not found')
print(value) # 输出:Not found
4.3 字典的keys()和values()方法
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
values = my_dict.values()
print(keys) # 输出:dict_keys(['a', 'b', 'c'])
print(values) # 输出:dict_values([1, 2, 3])
5. 集合
my_set = {1, 2, 3, 4, 5}
print(my_set)
5.1 集合操作 - 并集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set)
5.2 集合操作 - 交集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set)
6. 推导式
6.1 列表推导式
squares = [x**2 for x in range(5)]
print(squares) # 输出:[0, 1, 4, 9, 16]
6.2 字典推导式
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k: v*2 for k, v in my_dict.items()}
print(new_dict) # 输出:{'a': 2, 'b': 4, 'c': 6}
6.3 条件推导式
numbers = [1, 2, 3, 4, 5]
evens = [num for num in numbers if num % 2 == 0]
print(evens) # 输出:[2, 4]
7. 四大函数
7.1 enumerate函数
my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
7.2 zip函数
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for i, j in zip(list1, list2):
print(i, j)
7.3 map函数
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # 输出:[1, 4, 9, 16, 25]
7.4 filter函数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 输出:[2, 4, 6]
8. 条件语句
x = 10
if x > 5:
print("x is greater than 5")
9. 循环语句
9.1 for循环
for i in range(5):
print(i)
9.2 while循环
i = 0
while i < 5:
print(i)
i += 1
10. 异常处理
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
11. 文件读写
11.1 文件读取
with open('example.txt', 'r') as file:
content = file.read()
print(content)
11.2 文件写入
with open('example.txt', 'w') as file:
file.write('Hello, World!')
12. 模块导入
import math
print(math.sqrt(16)) # 输出:4.0
13. 函数
def greet(name):
print(f"Hello, {name}!")
greet("Bob")
14. 类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} barks!")
my_dog = Dog("Buddy")
my_dog.bark() # 输出:Buddy barks!
15. 继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} speaks!")
class Dog(Animal):
def bark(self):
print(f"{self.name} barks!")
my_dog = Dog("Buddy")
my_dog.speak() # 输出:Buddy speaks!
my_dog.bark() # 输出:Buddy barks!
关注公众号,获取200+本Python、人工智能相关学习资料