Python:list的列表生成式 for循环的升级版

列表生成式

学习资源:廖雪峰-Python教程
大家可以去我的github逛逛,定时更新程序测试题,和学习笔记:https://github.com/Neekky/Study-Python.git

  • 是Python内置的非常简单却强大的可以用来创建list的生成式。

如果要生成[1x1, 2x2, 3x3, …, 10x10]怎么做?方法一是循环:

L = []
for x in range(1, 11):
    L.append(x * x)
print(L)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list:

print([x * x for x in range(1, 11)])

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

print([x * x for x in range(1, 11) if x % 2 == 0])

[4, 16, 36, 64, 100]
#列表生成式可以嵌套
#由两个列表a,b
a=[i for i in range(1,4)]#生成一个list a
print(a)
b=[i for i in range(100,400) if i%100==0]
print(b)
#列表生成式是可以嵌套的,相当于两个for循环的嵌套
c=[m+n for m in a for n in b]
print(c)

[1, 2, 3]
[100, 200, 300]
[101, 201, 301, 102, 202, 302, 103, 203, 303]

上面的代码跟下面的代码是等价的

for m in a:
    for n in b:
        print(m+n,end=' ')
print() 

101 201 301 102 202 302 103 203 303 
# 嵌套的列表生成式也可以用条件表达式
c=[m+n for m in a for n in b if m+n<=250]
print(c)

还可以使用两层循环,可以生成全排列:

print([m + n for m in 'ABC' for n in 'XYZ'])

['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

在for循环中,可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:

d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
    print(k, '=', v)
    
x = A
y = B
z = C

因此,列表生成式也可以使用两个变量来生成list:

d = {'x': 'A', 'y': 'B', 'z': 'C' }
a=[k + '=' + v for k, v in d.items()]
print(a)
for k in a:
    print(k)

['x=A', 'y=B', 'z=C']
x=A
y=B
z=C

最后把一个list中所有的字符串变成小写:

L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])

['hello', 'world', 'ibm', 'apple']

猜你喜欢

转载自blog.csdn.net/qq_28766729/article/details/82747292