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

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']

pyDay8的更多相关文章

随机推荐

  1. web 前端规范实例

    <!DOCTYPE html> <html> <head> <title>tmall</title> <!-- 为了被搜索引擎作为流量 ...

  2. 在ubuntu 10.04 上QGIS的安装步骤

    进入管理员账户后,打开/etc/apt/sources.list. 添 加 deb http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubun ...

  3. LeetCode - Delete Duplicate Emails

    Discription:Write a SQL query to delete all duplicate email entries in a table named Person, keeping ...

  4. Linux系统下编译连接C源代码

    gcc test.c -o test 一步到位的编译指令 得到 test 文件 gcc test.c 得到 test.out 文件 gcc -g -c test.c -o test 只生成目标文件(. ...

  5. ipmi监控主机

    author: headsen   chen date: 2018-09-25  20:04:01 IPMI介绍       IPMI(Intelligent Platform Management ...

  6. Egret3D初步学习笔记三 (角色使用)

    一 Unity中编辑角色 仍然使用unity4.7.1_Egret3D_Dll.unitypackage. 里面含有一个角色. 二 查看人物的动画 选中lingtong 属性面板里有个Animator ...

  7. 【BZOJ2004】[Hnoi2010]Bus 公交线路 状压+矩阵乘法

    [BZOJ2004][Hnoi2010]Bus 公交线路 Description 小Z所在的城市有N个公交车站,排列在一条长(N-1)km的直线上,从左到右依次编号为1到N,相邻公交车站间的距离均为1 ...

  8. 【Android】Android背景选择器selector用法汇总

    一.创建xml文件,位置:drawable/xxx.xml,同目录下记得要放相关图片 <?xml version="1.0" encoding="utf-8&quo ...

  9. 在线预览文档(支持word、excel、ppt、pdf)+在线预览文档html版(转)

    1.首先上网搜索一下有什么解决方案 (1).将文档转换为html,只支持支持office文档 (2).将文档转换为flash,实现类似百度文库的效果,除支持office文档外还支持pdf (1) a. ...

  10. js封装正则验证

    //根据不同的验证内容,返回相应的正则表达式 function returnRegString(regName) { if (regName == "email") { retur ...