# -*- coding:utf-8 -*-
# author : Keekuun # 列表生成式,list
l1 = [i for i in range(10)]
# 或者
l2 = list(range(10))
print(l1, l2)
# type(l) list
# 打印:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] l3 = [x * x for x in range(1, 11) if x % 2 == 0]
print(l3) # 生成器,generator:惰性,可迭代
g = (i for i in range(10))
print(g)
# 打印:<generator object <genexpr> at 0x0000027EC76F5F10>
for i in g:
print(i)

列表生成式

可以使用两层循环,可以生成全排列:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现:
>>> import os 
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
... print(k, '=', v)
...
y = B
x = A
z = C
因此,列表生成式也可以使用两个变量来生成list:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
最后把一个list中所有的字符串变成小写:
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

生成器

1、’创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。

2、通过next()函数获得generator的下一个返回值

3、不断调用next(g)实在是太变态了,当值都被调用完之后,会抛出StopIteration的错误:正确的方法是使用for循环,因为generator也是可迭代对象

最新文章

  1. .Net 大型分布式基础服务架构横向演变概述
  2. C#学习笔记-Windows窗体基本功能(Login登录界面)
  3. social emotion computing-感情的分类
  4. Mathematics:Pseudoprime numbers(POJ 3641)
  5. 短信SMS的接收
  6. 汇编 db,dw,dd的区别
  7. EWS 通过SubscribeToPullNotifications订阅Exchange新邮件提醒
  8. 社交系统/社群系统“ThinkSNS+”H5及PC端终于来了!一起来“找茬”
  9. BZOJ 3265: 志愿者招募加强版 [单纯形法]
  10. 前端 CSS 目录
  11. python之面向对象进阶2
  12. C# windows 桌面控件的扩展
  13. js判断json对象中是否含有某个属性
  14. 有关ngui grid中去除一项后的排序问题
  15. windows安装及配置mysql5.7
  16. React Diff 算法
  17. HDU 4352 XHXJ&#39;s LIS (数位DP+LIS+状态压缩)
  18. codeforces793 B. Igor and his way to work (dfs)
  19. 神奇的sed替换
  20. cookie_session的详细用法

热门文章

  1. rsync+sersync实现文件同步
  2. L2 Regularization for Neural Nerworks
  3. pdo getLastInertID()无结果
  4. Join的7中情况
  5. [CF960G]Bandit Blues(第一类斯特林数+分治卷积)
  6. Python入门习题8.羊车门问题
  7. Linux之systemd服务配置及自动重启
  8. NGUI的窗体的推动和调节大小(drag object和drag resize object)
  9. Redis在windows下的环境搭建
  10. 屏幕坐标点转UGUI坐标【包含屏幕适配】