Files
python-book/01.基础语法/06.推导式.md
2025-09-20 14:54:32 +08:00

91 lines
2.1 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 推导式
## 推导式详细格式
```plain
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res:  列表生成元素表达式,可以是有返回值的函数。
for out_exp in input_list  迭代input_list将out_exp传入out_exp_res表达式中。
if out_exp == 2  根据条件过滤哪些值可以。
```
## 列表推导式
30以内所有能被3整除的数
```python
multiples = [i for i in range(30) if i % 3 == 0]
print(multiples)
```
30以内所有能被3整除的数的平方
```python
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 == 0]
print(multiples)
```
找到嵌套列表中名字含有两个及以上a的所有名字
```python
fruits = [['peach','Lemon','Pear','avocado','cantaloupe','Banana','Grape'],
['raisins','plum','apricot','nectarine','orange','papaya']]
print([name for lst in fruits for name in lst if name.count('a') >= 2])
```
## 字典推导式
将一个字典的key和value对调
```python
dic1 = {'a':1,'b':2}
dic2 = {dic1[k]: k for k in dic1}
print(dic2)
```
合并大小写对应的value值将k统一成小写
```python
dic1 = {'a':1,'b':2,'A':4,'Y':9}
dic2 = {k.lower():dic1.get(k.lower(),0) + dic1.get(k.upper(),0) for k in dic1.keys()}
print(dic2)
```
## 集合推导式
计算列表中每个值的平方,自带去重功能
```python
l = [1,2,3,4,1,-1,-2,3]
squared = {x**2 for x in l}
print(squared)
```
## 练习题
1. 过滤掉长度小于3的字符串列表并将剩下的转换成大写字母
2. 求(x,y)其中x是0-5之间的偶数y是0-5之间的奇数组成的元祖列表
3. 将1000以内的素数放入一个列表中
4. 推导式实现九九乘法表
```python
print("\n".join(["\t".join([f"{i}x{j}={i*j}" for j in range(1, i+1)]) for i in range(1,10)]))
# 1x1=1
# 2x1=2 2x2=4
# 3x1=3 3x2=6 3x3=9
# 4x1=4 4x2=8 4x3=12 4x4=16
# 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
# 6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
# 7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
# 8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
# 9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
```