列表解析

1.显示所有元素:for i in object:

In [1]: url = 'www.baidu.com'

In [2]: count = 0

In [3]: for i in url:   #遍历
   ...:     print i
   ...:     count += 1  #统计字符个数
   ...:     
w
w
w
.
b
a
i
d
u
.
c
o
m

In [4]: print count
13

2.计算100以内所有正整数的和

In [17]: sum = 0    #一定要初始化,否则会出错

In [18]: for i in range(1,101):     #注意 range 能取到 start 但是不能取到 end
    sum += i
print sum
   ....: 
5050


**range 和 xrange 的区别        #默认从 0 开始
range:在循环开始之前,直接在内存中生成一个序列
xrange:在使用的时侯才给值,可以很好的节约内存资源
zip:返回并行元素的元组列表,常用于在for循环中遍历数个序列

*for循环比while循环快,尤其是在遍历的时候

3.非完备遍历

In [23]: s = 'How are you these days ?'

In [24]: range(0,len(s),2)
Out[24]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

In [25]: for i in range(0,len(s),2):
   ....:     print s[i],        #在同一行输出,在 print 结尾i加上 , 即可
   ....:     
H w a e y u t e e d y  

In [26]: 

4.修改列表

In [28]: l = [1,2,3,4,5]

In [29]: for i in range(len(l)):
   ....:     l[i] += 1
   ....:     

In [30]: print l
[2, 3, 4, 5, 6]

In [31]: 

5.并行遍历

zip:
取得一个或多个序列为参数,将给定序列中的并排元素配成元组,返回这些元组的值
当参数长度不同时,zip会以最短的序列长度为准
在 for 循环中用于实现并行迭代

In [33]: l1 = [1,2,3,4,5,6,7]

In [34]: l2 = ['a','b','c','d','e','f','g','h']

In [35]: l3 = zip(l1,l2)

In [36]: zip(l1,l2)
Out[36]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g')]

In [37]: l3
Out[37]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g')]

In [38]: zip(l2,l1)
Out[38]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]

5.zip构造字典

In [43]: keys = [1,2,3,4,5,6,7]

In [44]: values = ['Mon','Tues','Wed','Thu','Fir','Srt','Sun']

In [45]: d = []         #不能定义为列表格式

In [46]: d= {}

In [47]: for k,v in zip(keys,values):
  d[k] = v
   ....: 

In [48]: d
Out[48]: {1: 'Mon', 2: 'Tues', 3: 'Wed', 4: 'Thu', 5: 'Fir', 6: 'Srt', 7: 'Sun'}

In [49]:

6.动态语言

(1) sys.getrefcount()
    增加对象的引用计数场景
        对象创建时:
        将对象添加进行容器时;类似于 :list.append()
        当对象被当作参数传递给函数时
        为对象创建另外变量名
    减少引用计数:
        引用此对象的变量名被显示销毁: delx
        给引用此对象的变量名重新赋值
        从容器中移除对象时,类似 list.pop()
        容器本身被销毁
(2)

6.迭代

重复做某事

可迭代对象(iterable):支持每次返回自己所包含的一个成员的对象
对象实现了__iter__方法
    序列类型:如 list ,str,tuple
    非序列类型:如 dict ,fil
    用户自定义的一些包含了 __iter__() 或 __getitem__()方法的类

In [1]: l1 = [1,2,3,4,5]

In [2]: dir(l1)     #查看 l1 的方法
Out[2]: 
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__delslice__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
In [3]: l1.__iter__()
Out[3]: <listiterator at 0x19ce350>     #返回迭代器地址

In [4]: l1.__iter__()
Out[4]: <listiterator at 0x19ce790>

迭代器:又称游标,它是程序设计的软件设计模式,是一种可在容器物件上实现元素遍历的接口
迭代器是一种特殊的数据结构,当然在oython中,它也是以对象的形式存在
    简单的理解方式:对于一个集体中的每一个元素,要想执行遍历,那么针对这个集体的迭代器定义了遍历集团中每一个元素的顺序或者方法

7.列表解析

根据已有列表生成新列表的方式

In [1]: l = [1,2,3,4]

In [2]: l1 = []

In [3]: for i in l:
   ...:     l1.append(i**2)
   ...: print l1
   ...: 
[1, 4, 9, 16]

In [4]: l3 = [i**2 for i in l1]     #相当于反向for循环,列表解析时,需要给其赋值

In [5]: print l3
[1, 16, 81, 256]

In [6]: 

In [12]: l1
Out[12]: [1, 4, 9, 16]

In [13]: l3 = [i**2 for i in l1 if i%2 == 0]    #嵌套if语句:if满足时,(即:做条件限制)

In [14]: print l3
[16, 256]

*打印出1-10中所有数的平方并且除以2

In [16]: for i in [i**2 for i in range(1,11)]:print i/2
0
2
4
8
12
18
24
32
40
50

*返回1-10内所有偶数的平方的除以2的结果  #扩展的列表解析的使用方式

In [17]: for i in [i**2 for i in range(1,11) if i%2 == 0]:print i/2
2
8
18
32
50

8.os模块

os.listdir('文件绝对路径')    #列出此目录下所有的文件,所组成的列表

In [23]: import os

In [24]: os.listdir('/home/kiosk/Desktop/manger/')
Out[24]: 
['\xe5\xa4\xa7\xe7\xa5\x9e.html',
 '.idea',
 'css',
 'font-awesome-4.7.0',
 'images',
 'js',
 'index.html',
 'icon.ico']



In [26]: filelist1 = os.listdir('/home/kiosk/Desktop/manger/')

*str.endswith('文件后缀')  #以此后缀结尾的文件

In [27]: str.
str.capitalize  str.format      str.isupper     str.rfind       str.startswith
str.center      str.index       str.join        str.rindex      str.strip
str.count       str.isalnum     str.ljust       str.rjust       str.swapcase
str.decode      str.isalpha     str.lower       str.rpartition  str.title
str.encode      str.isdigit     str.lstrip      str.rsplit      str.translate
str.endswith    str.islower     str.mro         str.rstrip      str.upper
str.expandtabs  str.isspace     str.partition   str.split       str.zfill
str.find        str.istitle     str.replace     str.splitlines  

In [27]: filelist2 = [i for i in filelist1 if i.endswith('.html')]

*取出此文件下以 .html 结尾的文件,并生成新的列表

In [28]: print filel
filelist1  filelist2  

In [28]: print filelist2
['\xe5\xa4\xa7\xe7\xa5\x9e.html', 'index.html']

*取出 etc 所有类型为目录的文件

9.列表 交叉相乘

In [33]: x1 = ['x','y','z']

In [34]: x2 = [1,2,3]

In [35]: l3 = [(i,j) for i in x1 for j in x2]

In [36]: print l3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]


*不让含 1 的项匹配
In [1]: l1 = ['x','y','z']

In [2]: l2 = [1,2,3]

In [3]: l3 = [(i,j) for i in l1 for j in l2 if j != 1]  #注意,第一个for语句也可以嵌套 if 语句

In [4]: print l3
[('x', 2), ('x', 3), ('y', 2), ('y', 3), ('z', 2), ('z', 3)]


*生成器:当需要每一次返回一个值时使用
    列表解析固然强大,但是非常占用资源
*()时返回迭代对象

In [1]: [i**2 for i in range(1,6)]
Out[1]: [1, 4, 9, 16, 25]

In [2]: (i**2 for i in range(1,6))
Out[2]: <generator object <genexpr> at 0x2f75820>

In [3]: (i**2 for i in range(1,6)).next()
Out[3]: 1

In [4]: (i**2 for i in range(1,6)).next()
Out[4]: 1

In [5]: i2 = (i**2 for i in range(1,6))

In [6]: print i2
<generator object <genexpr> at 0x2f75870>

In [7]: i2.next()
Out[7]: 1

In [8]: i2.next()
Out[8]: 4

In [9]: i2.next()
Out[9]: 9

In [10]: 

In [10]: i2.next()
Out[10]: 16

*注:此用法免得在内存中生成列表占用资源

In [11]: l3 = (i**2 for i in range(1,6) if i%3 == 0)

In [12]: l3.next()
Out[12]: 9

In [13]: for i in (i**2 for i in range(1,6) if i%3 == 0):print i
9

In [14]:

10.enumerat()函数的用法

range可在非完备遍历中用于生成索引偏移
    如故同时需要偏移索引和偏移元素,则可使用 enumerate()函数:梅举 返回一个生成器
*可以方便的获取序列中的索引

In [14]: url = 'www.baiddu.com'

In [15]: enumerate(url) 
Out[15]: <enumerate at 0x2f759b0>

In [16]: nihao = enumerate(url)     #方便的同时获取一个序列中的索引和元素本身

In [17]: nihao.next()   
Out[17]: (0, 'w')

In [18]: nihao.next()
Out[18]: (1, 'w')

In [19]: nihao.next()
Out[19]: (2, 'w')

In [20]: nihao.next()
Out[20]: (3, '.')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值