"""
列表生成式
"""
"""for循环举例"""
"""打印0到90,1,2,3,4,5,6,7,8,9,(结束位置)默认开始位置为0"""
for i in range(10):
print(i, end=",")
print()
"""打印5到105,6,7,8,9,10,(开始位置,结束位置)"""
for j in range(5, 11):
print(j, end=",")
print()
"""打印1到20的所有的偶数0,2,4,6,8,10,12,14,16,18,20,(开始位置,结束位置,步频)"""
for k in range(0, 21, 2):
print(k, end=",")
print()
"""
自动生成0到10的列表
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(10) 控制执行的次数,然后将i值打印
"""
a = [i for i in range(10)]
print(a)
"""
自动生成1到20 之间所有奇数(注意if中非0表示真)的列表
for i in range控制输出的范围和次数如果if i%2 为真则打印,然后将i输出
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
"""
b = [i for i in range(0, 20) if i % 2]
print(b)
"""
[0, 0, 1, 1, 2, 2]
类似下面的流程:
arr=[]
for i in rang(3):
for j in rang(2):
arr.append(i)
i 每次循环一次,都执行for j in range(2) 故一共打印了 3*2=6次
[0, 0, 1, 1, 2, 2]
"""
c = [i for i in range(3) for j in range(2)]
print(c)
"""
打印元组
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
"""
d = [(i, j) for i in range(3) for j in range(2)]
print(d)
"""
打印元组加强
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2)]
"""
e = [(i, j, k) for i in range(3) for j in range(2) for k in range(3)]
print(e)
|
|