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]
本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1796120
原文地址:http://90sirdb.blog.51cto.com/8713279/1796120