pyDay8

内容来自雪峰的官方网站。

List Comprehensions

1

>>> list(range(1, 3))
[1, 2]

2

>>> L = []
>>> for x in range(1 , 3):
...     L.append(x * x)
...
>>> L
[1, 4]

3

>>> L = [1, 2, 3]
>>> L
[1, 2, 3]
>>> L = [x * x for x in range(1 , 4)]
>>> L
[1, 4, 9]

4

>>> L = [x for x in range(1 , 100) if x % 2 == 0]
>>> L
[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]

5

>>> [m + n for m in 'abc' for n in 'xyz']
['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']

运用列表生成式,可以写出非常简洁的代码。

应用举例

1、列出当前目录下的所有文件:

>>> import os
>>> [f for f in os.listdir('.')]
['a.exe', 'prog1.cpp', 'prog1.exe', 'Sales_data.h', 'test.py', 'test.py.bak', '__pycache__', '新建文件夹']

2、将dict转化为list:

>>> d = {'lucy': 7, 'migo': 6, 'jack': 22}
>>> [x + '=' + str(y) for x,y in d.items()]
['migo=6', 'lucy=7', 'jack=22']

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

>>> L = ['migo', 'lucy', 'jack']
>>> [s.upper() for s in L]
['MIGO', 'LUCY', 'JACK']

 4、如果list中既包含字符串,又包含整数:

>>> L
['migo', 'lucy', 'jack', 19]
>>> [s.upper() for s in L if isinstance(s, str)]
['MIGO', 'LUCY', 'JACK']

 

posted @ 2017-02-19 14:26  xkfx  阅读(142)  评论(0)    收藏  举报