day10-列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

1、生成一个列表

a = [i for i in range(1,100) if i%2==1]
print(list(a))或print(a)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

或一句话输出
print([i for i in range(1,100) if i%2==0])
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]

2、生成[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]
写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来。

3、for循环后面还可以加上if判断,可以筛选出仅偶数的平方
print([x * x for x in range(1, 11) if x % 2 == 0])
[4, 16, 36, 64, 100]

对 numbers 的每个数求平方
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print([x * x for x in numbers])
[1, 4, 9, 16, 25, 36, 47, 84, 81, 100]

还可以使用两层循环,可以生成全排列:
print([m + n for m in 'ABC' for n in 'XYZ'])
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

4、列出当前目录下的所有文件和目录名
import os # 导入os模块,模块的概念后面讲到
print([d for d in os.listdir('.')]) # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

5、使用两个变量来生成list,类似于通过for循环迭代dict的items()取出key和value

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

6、把一个list中所有的字符串变成小写
L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])
['hello', 'world', 'ibm', 'apple']

如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:
L = ['Hello', 'World', 18, 'Apple', None]
print([i.lower() for i in L])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

使用内建的isinstance函数可以判断一个变量是不是字符串:
>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

通过添加if语句保证列表生成式能正确地执行:
[i.lower() for i in L if isinstance(i,str)]
['hello', 'world', 'apple']

或者用type()判断也可以,推荐用isinstance()
print([i.lower() for i in L if type(i)==str])

7、设置range中的步长
a = range(1,10)
print(list(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

b = range(1,10,2)
print(list(b))
[1, 3, 5, 7, 9]

猜你喜欢

转载自www.cnblogs.com/dxnui119/p/9829836.html