一、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

比较运算:

xy,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 "", 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语句也是可选的

仅用于占位,而后再填充相关语句时,可以使用passIn [41]: x=3

In [42]: y=4

In [45]: if x

print y

....:

4

In [48]: if x

....: print "the max number is: %d" %y

....: else:

....: print "the max number is: %d" %x

....:

the max number is: 4

In [51]: if x

....: 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,否则为expression2In [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

....: print x

....: x+=1

....:

0

1

2

3

4

5

6

7

8

9

In [68]: while x

print x,

x+=1

....:

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

In [70]: while x

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"] 以第一个列表中的元素为键,以第二个列表的元素为值生成字典d1In [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,bIn [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"]的所有元素定义为一个新列表l3In [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]: #返回了迭代器的内存地址

In [102]:

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

In [104]: i1.next

Out[104]:

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)

in ()

----> 1 i1.next()

StopIteration:

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

In [115]: i2.next

Out[115]:

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

In [9]: g1.next

Out[9]:

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]: 3In [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)

in ()

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

python中常见的流程结构-【Python2】04、Python程序控制结构相关推荐

  1. python中常见的流程结构-python常见对象的结构

    1 整数对象PyIntObject 整数对象是固定大小的Python对象,内部只有一个ob_ival保存实际的整数值. typedef struct { PyObject_HEAD long ob_i ...

  2. python中常见的流程结构-常见数据结构的 Python 实现(建议收藏)

    数据结构作为计算机基础的必修内容,也是很多大型互联网企业面试的必考题.可想而知,它在计算机领域的重要性. 然而很多计算机专业的同学,都仅仅是了解数据结构的相关理论,却无法用代码实现各种数据结构. 今日 ...

  3. python中常见的流程结构-Python学习笔记5程序的控制结构

    1.分支结构 (1)单分支结构 (2)二分支结构 (3)多分支结构 条件判断 (4)程序的异常处理 2.实例:身体质量指数BMI 思路一(国内,稍作修改就是国际): 思路二: 1 height,wei ...

  4. python中常见的流程结构-Python分支结构(switch)操作简介

    Python当中并无switch语句,本文研究的主要是通过字典实现switch语句的功能,具体如下. switch语句用于编写多分支结构的程序,类似与if-.elif-.else语句. switch语 ...

  5. python中常见的流程_Python面试中最常见的25个问题-结束

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 13)Python中的lambda表达式是什么? lambda表达式是一个匿名函数,通常用作代码行内的嵌入函数. 14)为什么Python中的lambda ...

  6. python中常见的漏洞_注意!Python中的10个常见安全漏洞及修复方法

    原标题:注意!Python中的10个常见安全漏洞及修复方法 源 /Python程序员 编写安全的代码很困难,当你学习一门编程语言.一个模块或框架时,你会学习其使用方法.在考虑安全性时,你需要考虑如何避 ...

  7. python 中常见的面试练习题

    python 中常见的面试题 语言特性 编码规范 数据类型-字符串 数据类型 - 列表 数据类型 - 字典 数据类型 - 综合 操作类题目 高级特性 正则表达式 其他内容 算法和数据结构 爬虫类 网络 ...

  8. python中数据分析的流程为-在数据分析流程中整合Python和R(一)

    EARL 是一个关于 R 语言的会议.今年的会议中却出现了大量关于Python的讨论.我认为,这个现象部分归功于在会议前一天举办的,关于整合 Python 和 R 的三小时研讨会. 本文是此系列三篇文 ...

  9. Python中常见的__init__.py是什么意思?详解Python import的方式和原理

    Python中常见的__init__.py是什么意思?详解Python import的方式和原理 1 什么是模块化编程? 2 __init__.py文件的作用 3 Python如何import第三方库 ...

最新文章

  1. 在asp.net中读取XML文件信息的4种方法
  2. 域控服务器发生w32time错误
  3. jvm:虚方法与非虚方法
  4. 科技核心期刊目录_中医学2019年版中国科技核心期刊目录(附影响因子)
  5. C#中typeof 与GetType()的区别和methodinfo、memberinfo反射
  6. Python 3.5.2 TypeError: a bytes-like object is required, not 'str’问题解决方案
  7. 档案盒正面标签制作_错题本科学制作方法、正确使用方式及窍门
  8. spss26没有典型相关性分析_SPSS在线_SPSSAU_SPSS典型相关分析
  9. android模拟器directx,DX千骑驱动器模拟器
  10. mongodb 副本集搭建
  11. Linux误删文件恢复
  12. php红包现金,php实现微信支付之现金红包
  13. 求和计算机教案,初中信息技术《Excel求和》教案
  14. Tensorflow图像识别-2
  15. 什么是SCRM 客户scrm管理系统 - whale 帷幄
  16. python字符串切片输出_python 字符串 切片
  17. 冬日舞会服务器维护中,冬日舞会
  18. 【物联网】微信小程序接入阿里云物联网平台
  19. Android实现背景图下拉回弹效果
  20. 如何实现表格左右两边的边框为0

热门文章

  1. Android Studio如何用真机调试
  2. NHibernate——Criteria条件查询
  3. 从红旗5.0提及——看Linux的内存办理
  4. [翻译]敏捷软件开发 一 之简要介绍
  5. NVisionXR_iOS教程二 —— 创建控制器和Vuforia对象
  6. [HNOI 2011]数矩形
  7. html中 alt 和 title 的区别
  8. mysql decimal(10,2)对应java类型
  9. 黑马程序员 - 接口、内部类和异常
  10. 转HTML中的table转为excel