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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法