文章目录
python的列表生成式
Python 列表生成式(List Comprehensions)是一种简洁且易于阅读的语法,用于从其他可迭代对象创建列表。它们提供了一种非常Pythonic的方式来创建列表,尤其是当你需要对一个序列中的每个元素执行某种操作或者创建一个满足特定条件的元素子集时。
列表生成式的基本语法如下:
[expression for item in iterable if condition]
- expression:这是一个关于item的表达式,用于生成列表中的元素。
- for item in iterable:这是一个for循环,遍历可迭代对象iterable。
- if condition(可选):这是一个条件表达式,用于过滤出满足条件的元素。
示例:
1.创建列表
创建一个1到10的列表
#for循环创建
a = []
for i in range(10):
a.append(i)
print(a)
#列表生成
b = [i for i in range(10)]
print(b)
#输出结果:
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 筛选偶数
从1到10中选出偶数
#利用for循环
c = []
for i in range(10):
if i % 2 == 0:
c.append(i)
print(c)
#列表生成式
d = [i for i in range(10) if i % 2 == 0]
print(d)
#输出结果:
#[0, 2, 4, 6, 8]
#[0, 2, 4, 6, 8]
3.生成99乘法表
生成99乘法表
#for循环生成
nine = []
for i in range(1, 10):
nine.append("\t".join([f"{i} * {j} = {i * j}" for j in range(1, i + 1)]))
print("\n".join(nine))
#列表生成式生成
nine1 =["\t".join([f"{i} * {j} = {i * j}" for j in range(1, i + 1)]) for i in range(1, 10)]
print("\n".join(nine1))
#输出结果:
#1 * 1 = 1
#2 * 1 = 2 2 * 2 = 4
#3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
#4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
#5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
#6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
#7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
#8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
#9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
#1 * 1 = 1
#2 * 1 = 2 2 * 2 = 4
#3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
#4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
#5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
#6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
#7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
#8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
#9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
4. 列表推导式中的嵌套循环
创建一个包含所有(x, y)对的列表,其中x取值范围为1到3,y取值范围为1到x(即1到1, 1到2, 1到3)
#for循环生成
num = []
for x in range(1, 4):
for y in range(1, x + 1):
num.append((x, y))
print(num)
#列表生成
pairs = [(x, y) for x in range(1, 4) for y in range(1, x + 1)]
print(pairs)
#输出结果:
#[(1, 1), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)]
#[(1, 1), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)]
列表生成式是Python中非常强大的工具,可以极大地简化代码,提高代码的可读性和执行效率。
标签:10,python,生成式,列表,range,print,生成 From: https://blog.csdn.net/2301_77698138/article/details/140405292