一、python的表达式和语句

1、表达式

   "某事",

         1个或多个操作数,和0个以上的操作符组成的序列就是表达式


2、语句

        “做某事”

           程序执行的操作都是语句来表达的,语句在程序中的执行顺序称为执行流或控制流,

语句是以分号结尾的单行代码(单行只有一个语句,分号可以省略),或者是语句块中的单行语句,


3、Python中常用的表达式操作符

数字运算:

      x+y,x-y,

      x*y,x//y,x%y,x/y, 

逻辑运算:

        x or y,x and y,not x

成员关系运算:

        x in y,x not in y

对象实例测试:

        x is y,x not is y

比较运算: 

          x<y,x>y,x<=y,x>=y,x==y,x!=y

位运算:

         x|y,x&&y,x^y,x<<y,x>>y

一元运算:

         -x,+x,~x

幂运算:

          x**y

索引和分片:

         x[i],x[i:j],x[x:j:stride]

调用:

          x(...)

取属性:

          x.attribut

元祖:(...)

序列:[...]

字典:{...}

三元选择表达式:x if y else z

匿名函数:lambda args: expression

生成器函数发送协议:yield x


运算优先级:

       (...),[...],{...}

        s[i],s[i:j]

        s.attribut

        s(...)

        -x,~x

         x**y

         *,/,//,%

         +,-

          <<,>>

          &,

          ^,

           |

           <,<=,>,>+,==,!=

           is,not is  

           in,not in  

           not

           and

            or

            lambda

          

4、常用语句

赋值语句:

       隐式赋值:import,from,def,class,for,函数参数

       元祖和列表分解赋值当赋值符号(=)的左侧为元祖或列表时,python会按照位置把右边的对象和左边的目标自左而右逐一进行配对儿,个数不同时会触发异常,此时可以以切片的方式进行

In [11]: l1=('Sun','Sat','Mon')

In [12]: l1
Out[12]: ('Sun', 'Sat', 'Mon')

In [13]: (x,y,z)=l1

In [14]: x
Out[14]: 'Sun'

In [15]: z
Out[15]: 'Mon'

      多重目标赋值:

In [21]: num1=num2=num3=11

In [23]: num1
Out[23]: 11

In [24]: num3
Out[24]: 11

In [25]: num1=22

In [26]: num1
Out[26]: 22

In [27]: num2
Out[27]: 11

In [28]: num3
Out[28]: 11

  增强赋值:+=,-=,*=,/=,//=,%=


调用语句:

print:打印对象

if/elif/else:条件判断

for/else:序列迭代

while/else:普通循环

pass:占位符

def:

return:

yield:

global:

raise:触发异常

import:

from:模块属性访问

class:

try/except/fimally:捕捉异常

del:删除引用

assert:调式检查

with/as:环境管理器


二、if 测试语句

1、Python的比较操作

所有的Python对象都支持比较操作

       可用于测试相等性、相对大小等

       如果是复合对象,Python会检查其所有部分,包括自动遍历各级嵌套对象,直到可以得出最终结果

测试操作符:

      “ ==”操作符测试值的相等性

      “is”表达式测试对象的一致性

         还有很多比如: <,>,=,

Python中不同类型的比较方法

       数字:通过相对大小进行比较

       字符串:按照字典次序逐字符进行比较

       列表和元组:自左至右比较各部分内容

       字典:对排序之后的(键、值)列表进行比较

Python中真和假的含义

       非零数字为真,否则为假

       非空对象为真,否则为假

       None则始终为假

组合条件测试

      and

      or

      not  非运算:返回True或False

注意:Python中,and和or运算会返回真或假的对象,而不是True或False,

        对象在本质上不是“真”,就是“假”

and和or是短路操作符

In [16]: 4=5
  File "<ipython-input-16-11e248ef17d4>", line 1
    4=5
SyntaxError: can't assign to literal


In [17]: 4==5
Out[17]: False

In [18]: a=1

In [19]: b=2

In [20]: a==2
Out[20]: False

In [21]: a<2
Out[21]: True

In [22]: a=b

In [23]: a
Out[23]: 2


2、if 测试的语法结构

if boolean_expression1:        #boolean_expression 布尔表达式可为真可为假

       suite1

elif boolean_expression2:

        suite2

else:

       else_suite


elif语句是可选的,else语句也是可选的

仅用于占位,而后再填充相关语句时,可以使用pass

In [41]: x=3

In [42]: y=4

In [45]: if x<y:            #单分支
    print y
   ....:     
4


In [48]: if x<y:              #双分支
   ....:     print "the max number is: %d" %y
   ....: else:
   ....:     print "the max number is: %d" %x
   ....:     
the max number is: 4


In [51]: if x<y:             #多分支
   ....:    print y
   ....:elif x>y:
   ....:    print x
   ....:else:    
   ....:   print x,y
   ....:     
4


3、if/else三元表达式

通常在为某变量设定默认值时通常用到的如下格式

if X:

      A = Y

else:

      A = Z

可以改写为如下简短格式

      A = Y if X else Z              #如果X是True则,A=Y,否则A=Z

其通用条件表达式语法格式为

        expression1 if boolean_expressionelse expression2

            表达式1            条件(布尔表达式)       表达式2

         如果boolean_expression的值为True,则条件表达式的结果为expression1,否则为expression2

In [52]:y=0

In [53]: x=1

In [54]: a=1

In [55]: b=2

In [58]: c=3

In [59]: i=b if x else c

In [60]: i
Out[60]: 2

In [61]: y=0

In [62]: i=b if y else c

In [63]: i
Out[63]: 3


三、while循环

1、循环机制及应用场景

while循环

       用于编写通用迭代结构

       顶端测试为真即会执行循环体,并会重复多次测试直到为假后执行循环后的其它语句


for循环

       一个通用的序列迭代器,用于遍历任何有序的序列对象内的元素

       可用于字符串、元组、列表和其它的内置可迭代对象,以及通过类所创建的新对象


Python也提供了一些能够进行隐性迭代的工具

       in成员关系测试

       列表解析

       map、reduce和filter函数


2、while循环

语法格式:

while boolean_expression:     

         while_suite

else:

         else_suite


else分支为可选部分

只要boolean_expression的结果为True,循环就会执行;

boolean_expression的结果为False时终止循环,此时如果有else分支,则会执行一次。

In [64]: url="www.magedu.com"

In [65]: while url:
   ....:     print url
   ....:     url=url[1:]
   ....:     
www.magedu.com
ww.magedu.com
w.magedu.com
.magedu.com
magedu.com
agedu.com
gedu.com
edu.com
du.com
u.com
.com
com
om
m

In [66]: 



In [338]: while url:print url;url=url[1:]      #2个语句可以用分号可以写在一行,冒号后面可以直接接一个语句
www.anyfish.com
ww.anyfish.com
w.anyfish.com
.anyfish.com
anyfish.com
nyfish.com
yfish.com
fish.com
ish.com
sh.com
h.com
.com
com
om
m

In [339]:



In [66]: x=0;y=10

In [67]: while x<y:
   ....:     print x
   ....:     x+=1
   ....:     
0
1
2
3
4
5
6
7
8
9

In [68]: while x<y:
    print x,
    x+=1
   ....:     

   
In [69]: x=0;y=100

In [70]: while x<y:
    print x,
    x+=1
   ....:     
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99


In [75]: while url:
    print url
    url=url[:-1]
else:
        print "gam over"
   ....:     
www.magedu.com
www.magedu.co
www.magedu.c
www.magedu.
www.magedu
www.maged
www.mage
www.mag
www.ma
www.m
www.
www
ww
w
gam over

In [76]:


3、break、continue 、pass 和else

break

          跳出所处的最近层循环

continue

          跳到所处的最近层循环的开始处

 break,continue 只能出现在循环结构中

pass

         占位语句

         当语法需要语句但还没有任何实用语句可写时使用

else代码块

         只要循环是正常终止,else分支就会执行

         在由于break语句、或由于返回语句(如果循环在函数或方法内)、或由于发生异常导致跳出循环,则else分支不会执行


4、while循环语法格式扩展

语法格式:

while boolean_expression1:

        while_suite

        if boolean_expression2: break

        if boolean_expression3: continue

else:

         else_suite


死循环:

while True:

      shile_suite


In [85]: url="www.magedu.com";x=0

In [86]: while url:
   ....:     print url
   ....:     url=url[:-1]
   ....:     x +=1
   ....:     if x>7:
   ....:         break
   ....: else:
   ....:     print "game over"
   ....:     
www.magedu.com
www.magedu.co
www.magedu.c
www.magedu.
www.magedu
www.maged
www.mage
www.mag

In [87]:


5、练习题

 1)逐一显示指定列表中的所有元素

In [128]: l1=["i","j","k"]

In [129]: count=0
In [130]: while count < len(l1):       #方法1
   .....:     print l1[count]
   .....:     count+=1
   .....:     
i
j
k

In [131]:
In [134]: while l1:                #方法2
   .....:     print l1[0]
   .....:     l1=l1[1:]
   .....:     
i
j
k

In [135]:
In [136]: while l1:              #方法3
    print l1[0]
    l1.pop(0)
   .....:     
i
j
k

In [137]:

 2)求100以内所有偶数之和

In [171]: x=0;y=0

In [172]: while x<100:          #100以内所有正整数之和
    x+=1
    y=x+y
    print y,
   .....:     
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990 1035 1081 1128 1176 1225 1275 1326 1378 1431 1485 1540 1596 1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 2278 2346 2415 2485 2556 2628 2701 2775 2850 2926 3003 3081 3160 3240 3321 3403 3486 3570 3655 3741 3828 3916 4005 4095 4186 4278 4371 4465 4560 4656 4753 4851 4950 5050

In [173]: 



In [173]: x=0;y=0

In [174]: while x<100:          #方法1
    x+=2
    y=x+y
    print y,
   .....:     
2 6 12 20 30 42 56 72 90 110 132 156 182 210 240 272 306 342 380 420 462 506 552 600 650 702 756 812 870 930 992 1056 1122 1190 1260 1332 1406 1482 1560 1640 1722 1806 1892 1980 2070 2162 2256 2352 2450 2550


In [177]: x=0;y=0

In [178]: while x<100:         
   .....:     y=x+y            
   .....:     x+=2             #为什么这样写就错了
   .....:     print y,         #y变小了
   .....:     
0 2 6 12 20 30 42 56 72 90 110 132 156 182 210 240 272 306 342 380 420 462 506 552 600 650 702 756 812 870 930 992 1056 1122 1190 1260 1332 1406 1482 1560 1640 1722 1806 1892 1980 2070 2162 2256 2352 2450

In [179]: 


In [198]: x=0;y=0

In [199]: while x<100:           #方法2
    x+=1
    if x%2==0:
        y=y+x
        print  y,
   .....:         
2 6 12 20 30 42 56 72 90 110 132 156 182 210 240 272 306 342 380 420 462 506 552 600 650 702 756 812 870 930 992 1056 1122 1190 1260 1332 1406 1482 1560 1640 1722 1806 1892 1980 2070 2162 2256 2352 2450 2550

In [200]: 


In [200]: x=0;y=0

In [201]: while x<100:         #方法3
    x+=1
    if x%2!=0:
        pass                 #这里也可以用continue代替
   .....:     else:
   .....:         y=y+x
   .....:         print y,
   .....:         
2 6 12 20 30 42 56 72 90 110 132 156 182 210 240 272 306 342 380 420 462 506 552 600 650 702 756 812 870 930 992 1056 1122 1190 1260 1332 1406 1482 1560 1640 1722 1806 1892 1980 2070 2162 2256 2352 2450 2550

In [202]:
In [5]: x=0;y=0

In [6]: while x<100:
    x+=1
    if x%2!=0:
        continue
    else:
        y+=x
else:
    print y,
   ...:     
2550              #应该这么写,只是求和,上面的列出了那么多结果,,



 3)逐一显示指定字典的所有键,并显示借宿后说明总键数

In [221]: d1={"x":1,'y':2,'z':3}

In [222]: keylist=d1.keys()

In [224]: while keylist:
    print keylist[0]
    keylist.pop(0)
else:
        print len(d1)
   .....:     
y
x
z
3

In [225]:

 4)创建一个包含了100以内的所有奇数列表

In [247]: x=1           #方法1

In [248]: l1=[]

In [249]: while x<100:
    l1.append(x)
    x+=2
else:
        print l1
   .....:     
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]


In [252]: x=0

In [253]: l1=[]

In [254]: while x<100:        #方法2
   .....:     x+=1
   .....:     if x%2!=0:
   .....:         l1.append(x)
   .....: else:
   .....:     print l1
   .....:     
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

In [255]:

 5)逆序逐一显示一个列表的所有元素

In [139]: l1=["i","j","k"]

In [140]: while l1:
   .....:     print l1[-1]
   .....:     l1.pop(-1)
   .....:     
k
j
i

In [141]:

 6)列表l1=[0,1,2,3,4,5,6],列表l2=["Sum","Mon","Tue","Fri","Sat"] 以第一个列表中的元素为键,以第二个列表的元素为值生成字典d1

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

In [278]: l2=["Sum","Mon","Tue","Wed","thu","Fri","Sat"]

In [279]: count=0

In [280]: d1={}

In [281]: while count < len(l1):
    d1[l1[count]]=l2[count]         #给键直接赋值
    count += 1
   .....:     print d1
   .....:     
{0: 'Sum'}
{0: 'Sum', 1: 'Mon'}
{0: 'Sum', 1: 'Mon', 2: 'Tue'}
{0: 'Sum', 1: 'Mon', 2: 'Tue', 3: 'Wed'}
{0: 'Sum', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'thu'}
{0: 'Sum', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'thu', 5: 'Fri'}
{0: 'Sum', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'thu', 5: 'Fri', 6: 'Sat'}

In [282]: count=0

In [283]: d1={}

In [284]: while count < len(l1):
    d1[l1[count]]=l2[count]
    count += 1
else:
   .....:     print d1
   .....:     
{0: 'Sum', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'thu', 5: 'Fri', 6: 'Sat'}


四、for循环

1、for循环

for循环

       一个通用的序列迭代器,用于遍历任何有序的序列对象内的元素

       可用于字符串、元组、列表和其它的内置可迭代对象,以及通过类所创建的新对象

语法格式:

for expression1 in iterable:

    for_suite

else:

    else_suite

通常,expression或是一个单独的变量,或是一个变量序列,一般以元组的形式给出

如果以元组或列表用于expression,则其中的每个数据项都会拆分到表达式的项

例如:

T=[(1,2),(3,4),(5,6),(7,8)]

for (a,b) in T:

    print a,b

In [293]: url="www.anyfish.com"

In [294]: for x in url:
   .....:     print x
   .....:     
w
w
w
.
a
n
y
f
i
s
h
.
c
o
m

In [295]: 



In [305]: sum=0

In [306]: for i in range(101):
    sum+=i
else:
    print sum
   .....:     
5050

2、for循环形式扩展

语法格式:

for expressionin iterable:

    for_suite

    if boolean_expression2: break

    if boolean_expression3: continue

else:

    else_suite


3、编写循环的技巧

for循环比while循环执行速度快

Python提供了两个内置函数,用于在for循环中定制特殊的循环

         range或xrange

                   range: 一次性地返回连续的整数列表

                   xrange:一次产生一个数据元素,相较于range更节约空间

range函数用于非完备遍历

         用于每隔一定的个数元素挑选一个元素:

In [318]: s="How are you these days?"

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

In [322]: for i in range(0,len(s),2):print s[i],
H w a e y u t e e d y ?

In [323]: for i in range(0,len(s),2):print s[i],
H w a e y u t e e d y ?

In [324]: for i in range(0,len(s),2):
   .....:     print s[i]
   .....:     
H
w
a
e
y
u
t
e
e
d
y
?

修改列表:   

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

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

In [353]: l
Out[353]: [2, 3, 4, 5, 6]


       zip

                   返回并行的元素元组的列表,常用于在for循环中遍历数个序列


并行遍历:

zip

        取得一个或多个序列为参数,将给定序列中的并排的元素配成元 组,返回这些元组的列表

               当参数长度不同时,zip会以最短序列的长度为准

可在for循环中用于实现并行迭代:

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

In [355]: l2=["a","b","c","d","e","f","g","h"]

In [356]: zip(l1,l2)
Out[356]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

In [357]: t1=(1,2,3,4,5)

In [358]: t2=("a","b","c","d","e","f","g","h")

In [359]: zip(t1,t2)
Out[359]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

In [360]:

zip也常用于动态构成字典:

In [360]: d1={}

In [361]: for (i,j) in zip(l1,l2):     #l1和l2上面的例子定义了
   .....:     d1[i]=j
   .....: else:
   .....:     print d1
   .....:     
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}


用户输入数据创建一个列表:

In [19]: test=[]

In [20]: while True:
    x=raw_input("Enter an entry: ")
    if x=='q' or x=='quit':
        break
    else:
        test.append(x)
        print test
   ....:         
Enter an entry: 1
['1']
Enter an entry: 2
['1', '2']
Enter an entry: a
['1', '2', 'a']
Enter an entry: b
['1', '2', 'a', 'b']
Enter an entry: hello
['1', '2', 'a', 'b', 'hello']
Enter an entry: q

In [21]: test
Out[21]: ['1', '2', 'a', 'b', 'hello']


4、练习题

1)逐一分开显示指定字典d1中的所有元素,类似如下:

      k1 v1

      k2 v2

      ...

In [25]: d1={"a":1,"b":2,"c":3,"d":4}

In [26]: d1.
d1.clear       d1.items       d1.pop         d1.viewitems
d1.copy        d1.iteritems   d1.popitem     d1.viewkeys
d1.fromkeys    d1.iterkeys    d1.setdefault  d1.viewvalues
d1.get         d1.itervalues  d1.update      
d1.has_key     d1.keys        d1.values      

In [26]: d1.items()
Out[26]: [('a', 1), ('c', 3), ('b', 2), ('d', 4)]

In [27]: d1.keys()
Out[27]: ['a', 'c', 'b', 'd']

In [28]: d1.values()
Out[28]: [1, 3, 2, 4]

In [30]: for (i,j) in zip(d1.keys(),d1.values()):  #可以直接写成 for (i,j) in d1.items()
    print i,j
   ....:     
a 1
c 3
b 2
d 4

2)逐一显示列表中l1=["Sun","Mon2","Tue","Wed","Thu","Fri","Sat"]中的索引为奇数的元素

In [41]: range(10)
Out[41]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [42]: range(10,2)
Out[42]: []

In [43]: range(0,10,2)
Out[43]: [0, 2, 4, 6, 8]

In [44]: l1=["Sun","Mon2","Tue","Wed","Thu","Fri","Sat"]

In [45]: for i in range(1,len(l1),2):
   ....:     print l1[i]
   ....:     
Mon2
Wed
Fri

In [46]:

3)将属于列表l1=["Sun","Mon2","Tue","Wed","Thu","Fri","Sat"],但不属于l2=["Sun","Mon2","Tue","Thu","Sat"]的所有元素定义为一个新列表l3

In [76]: l1=["Sun","Mon2","Tue","Wed","Thu","Fri","Sat"]

In [77]: l2=["Sun","Mon2","Tue","Thu","Sat"]

In [78]: l3=[]

In [85]: for i in l1:                                                      
   ....:     if i not in l2:
   ....:         l3.append(i)
   ....: else:
   ....:     print l3
   ....:     
['Wed', 'Fri']

4)已知列表namelist=["stu1","stu2","stu3","stu4","stu5","stu6","stu7"],removelist=["stu3","stu7","stu9"],请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可)

In [80]: namelist=["stu1","stu2","stu3","stu4","stu5","stu6","stu7"];removelist=["stu3","stu7","stu9"]

In [81]: for i in removelist:
   ....:     if i in namelist:   
   ....:         namelist.remove(i)
   ....: else:
   ....:     print namelist
   ....:     
['stu1', 'stu2', 'stu4', 'stu5', 'stu6']

In [82]:


五、python迭代器

1、迭代

迭代重复做一件事

iterable(可迭代)对象:

       支持每次返回自己所包含的一个成员的对象

       对象实现了__iter__方法

              序列类型,如: list,str, tuple

              非序列类型,如: dict,file

              用户自定义的一些包含了__iter__() 或__getitem__() 方法的类


2、迭代器

迭代器

       迭代器(iterator)又称游标(cursor),它是程序设计的软件设计模式,是一种可在容器物件(container,如列表等)上实现元素遍历的接口

迭代器是一种特殊的数据结构,当然在Python中,它也是以对象的形式存在的

       简单理解方式:对于一个集体中的每一个元素,想要执行遍历, 那么针对这个集体的迭代器定义了遍历集体中每一个元素的顺序或者方法

在Python中,迭代器是遵循迭代协议的对象

使用iter()可从任何序列对象中得到迭代器

若要实现迭代器,需要在类中定义next()方法(Python 3中是__next__())

要使得迭代器指向下一个元素,则使用成员函数next()

        在Python中,是函数next(),而非成员函数

当没有元素时,则引发StopIteration异常


for循环可用于任何可迭代对象:

        for循环开始时,会通过迭代协议传递给iter()内置函数,从而能够从可迭代对象中获得一个迭代器,返回的对象含有需要的next 方法

In [98]: l1
Out[98]: ['Sun', 'Mon2', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

In [99]: l1.
l1.append   l1.extend   l1.insert   l1.remove   l1.sort     
l1.count    l1.index    l1.pop      l1.reverse  

In [99]: dir(l1)
Out[99]: 
['__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 [101]: l1.__iter__()
Out[101]: <listiterator at 0x1b1a4d0>      #返回了迭代器的内存地址

In [102]: 



In [103]: i1=l1.__iter__()

In [104]: i1.next
Out[104]: <method-wrapper 'next' of listiterator object at 0x19fcd10>

In [105]: i1.next()
Out[105]: 'Sun'

In [106]: i1.next()
Out[106]: 'Mon2'

In [107]: i1.next()
Out[107]: 'Tue'

In [108]: i1.next()
Out[108]: 'Wed'

In [109]: i1.next()
Out[109]: 'Thu'

In [110]: i1.next()
Out[110]: 'Fri'

In [111]: i1.next()
Out[111]: 'Sat'

In [112]: i1.next()           #遍历完后会报一个异常
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-112-be7912f76fe0> in <module>()
----> 1 i1.next()

StopIteration: 



In [114]: i2=iter(l1)     #使用iter()可从任何序列对象中得到迭代器

In [115]: i2.next
Out[115]: <method-wrapper 'next' of listiterator object at 0x1b2d110>

In [116]: i2.next()
Out[116]: 'Sun'

In [117]: i2.next()
Out[117]: 'Mon2'

In [118]:


六、列表解析

1、python列表解析

列表解析是python迭代机制的一种应用,它常用于实现创建新的列表,因此要放置于[]中   #高效

语法:

       [expression for iter_var in iterable]

       [expression for iter_var in iterable if cond_expr]

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

In [127]: l2=[]

In [128]: for i in l1:
    l2.append(i**2)
else:
    print l2
   .....:     
[1, 4, 9, 16, 25]

In [129]: 


In [130]: l3=[i**2 for i in l1];print l3
[1, 4, 9, 16, 25]

In [131]: 


In [131]: l4=[i**2 for i in l1 if i>3];print l3
[16, 25]


2、练习

       求1-10范围内正整数的平方除以2的值

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


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

In [138]:

       求1-10范围内所有偶数的平方除以2的值

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

In [140]:

  将/var/log目录下所有以.log结尾的文件名组成一个新的列表

In [142]: import os

In [143]: os.listdir('/var/log')
Out[143]: 
['secure-20160908',
 'vmware-caf',
 'audit',
 'anaconda.ifcfg.log',
 'anaconda.syslog',
 'maillog',
 'wtmp',
 'ConsoleKit',
 'secure-20160902',
 'cron',
 'anaconda.program.log',
 'dmesg.old',
 'messages',
 'messages-20160908',
 'spooler',
 'cron-20160912',
 'cron-20160908',
 'spooler-20160902',
 'anaconda.log',
 'anaconda.storage.log',
 'btmp',
 'spooler-20160908',
 'yum.log',
 'anaconda.yum.log',
 'btmp-20160902',
 'dracut.log',
 'vmware-vmsvc.log',
 'tallylog',
 'secure',
 'messages-20160912',
 'vmware-install.log',
 'lastlog',
 'maillog-20160902',
 'anaconda.xlog',
 'maillog-20160912',
 'spooler-20160912',
 'messages-20160902',
 'dmesg',
 'cron-20160902',
 'secure-20160912',
 'boot.log',
 'maillog-20160908']

In [144]: filelist1=os.listdir('/var/log')

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

In [146]: filelist2
Out[146]: 
['anaconda.ifcfg.log',
 'anaconda.program.log',
 'anaconda.log',
 'anaconda.storage.log',
 'yum.log',
 'anaconda.yum.log',
 'dracut.log',
 'vmware-vmsvc.log',
 'vmware-install.log',
 'boot.log']

In [147]: 



In [147]: help(str.endswith)   #字符串以什么字符结尾


Help on method_descriptor:

endswith(...)
    S.endswith(suffix[, start[, end]]) -> bool
    
    Return True if S ends with the specified suffix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.
(END)

  for 嵌套 for:

In [148]: l1=['x','y','z']

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

In [150]: l3=[(i,j) for i in l1 for j in l2];print l3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

In [151]:


3、生成器表达式

生成器表达式并不真正创建数字列表, 而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目“产生”(yield)出来

      生成器表达式使用了“惰性计算”或称作“延迟求值”的机制

序列过长,并且每次只需要获取一个元素时,应当考虑使用生成器表达式而不是列表解析

      生成器表达式于python 2.4引入

语法:

       (expr for iter_var in iterable)

       (expr for iter_var in iterable if cond_expr)


列表解析和生气器的关系就像range和xrange一样

In [152]: [i**2 for i in range(1,11)]
Out[152]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [153]: [i**2 for i in xrange(1,11)]
Out[153]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [154]: (i**2 for i in range(1,11))
Out[154]: <generator object <genexpr> at 0x1cdd4b0>       #返回一个生成器地址

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

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

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


In [160]: g1=(i**2 for i in range(1,11))        ########

In [161]: g1.next()
Out[161]: 1

In [162]: g1.next()
Out[162]: 4

In [163]: g1.next()
Out[163]: 9

In [164]:

函数中使用yield,会返回一个生成器对象

In [1]: def genNum(x):
   ...:     y=0
   ...:     while y<=x:
   ...:         yield y
   ...:         y+=1
   ...:         

In [3]: type(genNum)
Out[3]: function

In [5]: g1=genNum(10)

In [6]: type(g1)
Out[6]: generator

In [8]: g1.
g1.close       g1.gi_frame    g1.next        g1.throw
g1.gi_code     g1.gi_running  g1.send        

In [8]: g1
Out[8]: <generator object genNum at 0x13f9a00>

In [9]: g1.next
Out[9]: <method-wrapper 'next' of generator object at 0x13f9a00>

In [10]: g1.next()
Out[10]: 0

In [11]: g1.next()
Out[11]: 1

In [12]: g1.next()
Out[12]: 2

In [13]: g1.next()
Out[13]: 3
In [48]: def genNum(x):
    y=0
    while y<=x:
        yield y**2
        y+=1
   ....:         

In [49]: g1=genNum(5)

In [50]: g1.next()
Out[50]: 0

In [51]: g1.next()
Out[51]: 1

In [52]: g1.next()
Out[52]: 4

In [53]: g1.next()
Out[53]: 9

In [54]: g1.next()
Out[54]: 16

In [55]: g1.next()
Out[55]: 25

In [56]: g1.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-56-9066a8f18086> in <module>()
----> 1 g1.next()

StopIteration: 



In [60]: g1=genNum(5)

In [61]: for i in g1:print i
0
1
4
9
16
25


4、产生偏移和元素

enumerate

       range可在非完备遍历中用于生成索引偏移,而非偏移处的元素

       如果同时需要偏移索引和偏移元素,则可以使用enumerate()函数

       此内置函数返回一个生成器对象

In [177]: url="www.anyfish.com"

In [178]: g1=enumerate(url)

In [179]: g1.next()
Out[179]: (0, 'w')

In [180]: g1.next()
Out[180]: (1, 'w')

In [181]: g1.next()
Out[181]: (2, 'w')

In [182]: g1.next()
Out[182]: (3, '.')

In [183]: g1.next()
Out[183]: (4, 'a')

In [184]: