python3中的列表生成式

列表生成式

列表生成式是python内置的创建列表的一种方法。

如果要生成列表[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],我们可以使用list(range(1,11)).

但是如果要生成[1x1, 2x2, 3x3, …, 10x10]怎么办?

第一种方法:使用循环

for x in range(1,11):
	l.append(x*x)

但是循环太繁琐,使用列表生成式仅仅用一句话就可以替代上面的循环:

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

for 循环后面也可以跟上判断,这样我们可以筛选不同条件下的参数,例如求偶数或者奇数的和

[x*x for x in range(1,11) if x % 2 == 0]#求偶数两两乘积
[x*x for x in range(1,11) if x % 2 == 1]#求奇数数两两乘积

#计算结果
[4, 16, 36, 64, 100]
[1, 9, 25, 49, 81]

在for循环后面也可以在跟一个for循环,生成全排列:

[x + y for x in 'ABC' for y in '123']
#结果
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

三层或者三层以上的循环很少用到列表生成式

for 循环可以同时对两个甚至多个变量进行循环,因此列表生成式可以使用两个变量生成lsit:

mydict = {'A':'1','B':'2','C':'5'}
[x + '=' + y  for x,y in mydict.items()]
#结果
['C=5', 'B=2', 'A=1']

使用列表生成式可以把所有的字符串变为小写:

L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
#结果
['hello', 'world', 'ibm', 'apple']

但是如果列表中的元素并不全是字符串,使用lower时就会出错,

L = ['Hello', 'World', 18, 'Apple']
[s.lower() for s in L]
#结果
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    [s.lower() for s in L]
  File "<pyshell#6>", line 1, in <listcomp>
    [s.lower() for s in L]
AttributeError: 'int' object has no attribute 'lower'

因此需要对元素类型进行判断,对元素的类型我们可以使用type()或者isinstance,在此建议使用isinstance:

isinstance用法如下:

li = ['ss',1,1.0]
isinstance(li[0],str)
isinstance(li[1],int)
isinstance(li[2],int)
#结果
True
True
False

因此当出现非字符串类型的元素时,可以使用isinstance判断:

L = ['Hello', 'World', 18, 'Apple']
[s.lower() for s in L if isinstance(s,str)]
[s.lower() for s in L if type(s) == str]
#结果
['hello', 'world', 'apple']
['hello', 'world', 'apple']

参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017317609699776,自用

猜你喜欢

转载自blog.csdn.net/weixin_43245453/article/details/90045988