编程 Python 题102

##

Python 是一种流行的编程语言,以其易用性和强大的功能而闻名。以下是 15 道 Python 编程题,涵盖了各种 Python 概念和技能:## 1. 取列表中最大值和最小值
```python
my_list = [1, 2, 3, 4, 5]
print(max(my_list)) # 输出:5
print(min(my_list)) # 输出:1
```
## 2. 查找列表中元素的索引
```python
my_list = ["apple", "banana", "cherry"]
index = ("cherry") # 输出:2
```
## 3. 创建一个集合
```python
my_set = {"apple", "banana", "cherry"}
```
## 4. 添加元素到集合
```python
("orange")
```
## 5. 创建一个字典
```python
my_dict = {"name": "John", "age": 30}
```
## 6. 获取字典中的值
```python
print(my_dict["name"]) # 输出:John
```
## 7. 循环字典中的键值对
```python
for key, value in ():
print(key, ":", value)
```
## 8. 使用 lambda 函数排序列表
```python
my_list = [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]
sorted_list = sorted(my_list, key=lambda x: x["age"])
```
## 9. 使用 map 函数应用函数到列表
```python
def square(x):
return x * x
my_list = [1, 2, 3, 4, 5]
squared_list = map(square, my_list)
```
## 10. 使用 filter 函数筛选列表
```python
def is_even(x):
return x % 2 == 0
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = list(filter(is_even, my_list))
```
## 11. 使用 reduce 函数累加列表
```python
from functools import reduce
my_list = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, my_list)
```
## 12. 使用生成器生成斐波那契数列
```python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
```
## 13. 使用正则表达式匹配字符串
```python
import re
pattern = r"^[a-zA-Z0-9]+$"
string = "my_string"
match = (pattern, string) # True
```
## 14. 创建和使用自定义类
```python
class Person:
def __init__(self, name, age):
= name
= age
def get_name(self):
return
def get_age(self):
return
john = Person("John", 30)
print(john.get_name()) # 输出:John
```
## 15. 使用异常处理
```python
try:
# ...
except Exception as e:
# ...
finally:
# ...
```

2024-12-21


上一篇:Python中卷积编程基础指南

下一篇:Python 程序设计范本