您的位置:首页 > 编程语言 > Python开发

Python 列表生成式

2016-07-05 23:10 363 查看

1.1 列表生成式

Python内置的非常简单却强大的可以用来创建list的生成式。
要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做
>>> L = []
>>> for i in range(1, 6): --循环
... L.append(i * i)
...
>>> L
[1, 4, 9, 16, 25]
>>> [x * xfor x in range(1, 6)] --列表生成式
[1, 4, 9, 16, 25]
x * x要生成的元素放在前面,后还可以跟if语句
>>> [x * xfor x in range(1, 6) if x % 2 == 0]
[4, 16]
两层循环,生成全排列
>>> [m + nfor m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX','CY', 'CZ']
列当前目录下所有文件和目录
>>> import os
>>> [d for d inos.listdir('.')] --发现含隐藏文件也被列出来了
['.tcshrc', '.dmrc', 'Desktop', '.gconf','.redhat', '.gnome2_private', '.bashrc', 'Python-3.5.0b4', '.python_history','redis', '.cshrc', '.gtkrc-1.2-gnome2', 'python', '.chewing', '.Trash','.gnome', '.nautilus', '.kde', '.scim', '.lesshst', '.bash_logout','Python-3.5.0b4.tgz', '.gconfd', '.xsession-errors', '.bash_profile','.Xauthority', '.gnome2', '.ICEauthority', '.metacity', '.gstreamer-0.10','.bash_history', '.eggcups', '.mysql_history', 'shell']
dict的列表生成式
>>> d = {'x': 'A', 'y': 'B', 'z':'C' }
>>> [ k +'=' + v for k, v in d.items()] - dict的key,value同时迭代,是不是很类似
['y=B', 'x=A', 'z=C']
>>> L = ['Hello', 'World', 'IBM','Apple']
>>> [s.lower()for s in L]
['hello', 'world', 'ibm', 'apple']
练习部分
由于L中含整数和None,不能仅用lower函数。
>>> L = ['Hello', 'World', 18,'Apple', None]
>>> l_r = []
>>> len(L)
5
>>> for i in L:
... if isinstance(i,str):
... l_r.append(i.lower())
... else:
... l_r.append(i)
...
>>> l_r
['hello', 'world', 18, 'apple', None]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  列表 python 生成式