今天我们来学习一下怎么生成一个列表list, 假如我们要生成一个列表[1,2,3,4,5,6,7,8,9],我们回想一下,我们有几种方法。
首先,最笨的方法,直接写出,当然此方法稍微扩展一些就不可使用,比如说如果需要生成的列表元素为几百上千个。其次,我们可以利用range()函数来生成如上的list.如下:
>>> list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
最后,我们还可以利用循环语句来实现,首先定义一个空list ,然后利用循环语句不断扩充元素。例如:
>>> L = []
>>> for x in range(1,11):
L.append(x)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
但我们看到使用for循环语句还是比较麻烦的,需要使用好几行语句,有没有一种方法使用一句就可以实现呢?这就是本节要学习的知识,列表生成式。生成如上的list, 我们只需要如下的一句语句就可以。
[x for x in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
而且,列表生成式还可以镶嵌判断语句,如下:
>>> [x for x in range(1,11) if x%2 == 0]
[2, 4, 6, 8, 10]
当然也可以包含一些运算在其中,如下:
>>> [x*x for x in range(1,11) if x%2 == 0]
[4, 16, 36, 64, 100]
另外,我们还可以在其中使用两层以上的循环语句,
>>> [m+n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
>>> d = {'x':'A','y':'B','z':'C'}
>>> [k + '=' + v for k,v in d.items()]
['x=A', 'y=B', 'z=C']
>>> for k,v in d.items():
print(k,'=',v)
x = A
y = B
z = C
最后,把list中的所有大写元素变为小写。
>>> L = ['Hello','World','Apple','IBM']
>>> [s.lower() for s in L]
['hello', 'world', 'apple', 'ibm']
>>> L1 = ['Hello','World',34,'Apple',None]
>>> [s.lower() for s in L1]
Traceback (most recent call last):
File "", line 1, in
[s.lower() for s in L1]
File "", line 1, in
[s.lower() for s in L1]
AttributeError: 'int' object has no attribute 'lower'
如上所示,如果list中包含非字符串元素,会报错,因为元素34不能小写,没有lower()方法。此时我们可以结合判断语句,筛选出字符串元素。
>>> [s.lower() for s in L1 if isinstance(s,str) == True]
['hello', 'world', 'apple']