Python中的正则表达式与数学应用
立即解锁
发布时间: 2025-08-22 01:48:48 阅读量: 7 订阅数: 13 


Python数据分析与统计学入门指南
### Python 中的正则表达式与数学应用
#### 回顾练习
在深入学习正则表达式和数学应用之前,先来看一些关于 Python 容器操作的回顾练习。
1. **列表与元组的转换**
- 将元组转换为列表:使用 `list()` 方法,例如 `list((1,2,3))`。
- 将列表转换为元组:使用 `tuple()` 方法,例如 `tuple([1,2,3])`。
2. **使用字典推导式创建字典**
```python
# list containing keys
l = list('abcdef')
# list containing values
m = list(range(6))
# dictionary comprehension
x = {i:j for i,j in zip(l,m)}
print(x)
```
3. **代码错误判断**
- 选项 a:`'abc'[0]='d'`,字符串是不可变对象,此操作会导致错误。
- 选项 b:`list('abc')[0]='d'`,列表是可变对象,此操作允许,不会报错。
- 选项 c:`tuple('abc')[0]='d'`,元组是不可变对象,此操作会导致错误。
- 选项 d:`dict([('a',1),('b',2)])[0]=3`,字典是可变对象,此操作允许,不会报错。
所以正确选项为 b 和 d。
4. **计算句子中元音字母的数量**
```python
message = "Every cloud has a silver lining"
m = message.lower()
count = {}
vowels = ['a', 'e', 'i', 'o', 'u']
for character in m:
if character.casefold() in vowels:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
```
5. **代码输出判断**
```python
x = 1,2
y = 1,
z = (1,2,3)
print(type(x) == type(y) == type(z))
```
输出为 `True`,因为这三种方式都是定义元组的有效方式。
6. **嵌套字典的访问**
```python
numbers = {
'English': {'1': 'One', '2': 'Two'},
'Spanish': {'1': 'Uno', '2': 'Dos'},
'German': {'1': 'Ein', '2': 'Zwei'}
}
print(numbers['Spanish']['2'])
```
输出为 `'Dos'`,这里运用了嵌套字典的概念。
7. **向字典中添加元素**
```python
eatables = {'chocolate': 2, 'ice cream': 3}
# If statement
if 'biscuit' not in eatables:
eatables['biscuit'] = 4
# setdefault method(alternative method)
eatables.setdefault('biscuit', 4)
print(eatables)
```
8. **列表操作**
```python
odd_numbers = list(range(1, 20, 2))
# Add the element 21 at the end
odd_numbers.append(21)
# insert the number 23 at the 4th position
odd_numbers.insert(3, 23)
# To this list, add another list containing even numbers from 1 to 20
even_numbers = list(range(2, 20, 2))
odd_numbers.extend(even_numbers)
# find the index of the number 15
print(odd_numbers.index(15))
# remove and return the last element
print(odd_numbers.pop())
# delete the 10th element
del odd_numbers[9]
# filter this list with all numbers less than or equal to 13
nos_less_13 = filter(lambda x: x <= 13, odd_numbers)
print(list(nos_less_13))
# use the map function to create a list containing squares
squared_list = map(lambda x: x**2, odd_numbers)
# use list comprehension for the new list
new_list = [x/2 if x % 2 == 0 else x for x in odd_numbers]
print(new_list)
```
#### 正则表达式
正则表达式是一种包含字符(如字母和数字)和元字符(如 `*` 和 `$` 符号)的模式。它可用于搜索、替换或提取具有可识别模式的数据,如日期、邮政编码、HTML 标签、电话号码等,还可用于验证密码和电子邮件地址等字段,确保用户输入的格式正确。
##### 解决正则表达式问题的步骤
1. **导入 `re` 模块**
```python
import
```
0
0
复制全文
相关推荐










