推导式

 

循环:

test = [1,2,3,4,5,6,7,7,8]

for i in test:
  if int(i)>3:
  print(i)

 

列表推导式子:

test = [1,2,3,4,5,6,7,7,8]

t1=[i for i in test if int(i)>3]
print(t1)

mytest=["xiaofan","xiaof","xiaofanfan"]
mytest1=[i for i in mytest if len(i)<6]
print(mytest1)

#生成列表

 

把上面[]换成()则变成生成器:(访问可以使用next(x)方法,在python2中可以用.next()访问)

t2=(i for i in test if int(i)>3)
print(t2)
print(next(t2))

#访问完所有数据后继续访问会报 stopIteration异常

 

m = [[1,2,3],[2,3,4],[3,4,5]]
m1=[i[0] for i in m]
m2=[m[i][i] for i in range(len(m))]
print(m1)
print(m2)

[1, 2, 3]
[1, 3, 5]

 

enumerate()返回两个值,一个是序列的下标,一个是下标对应的值:

for i,j in enumerate('fan'):
  print(i,j)

0 f
1 a
2 n

 

打印成绩大于90分的:

chengji=[[89,98,66,99,100,56],[77,97,66,67,78,42]]

cj=[m for kemu in chengji for m in kemu if int(m)>90]
print(cj)

[98, 99, 100, 97]

 

posted @ 2016-09-23 21:14  xuanhui  阅读(150)  评论(0编辑  收藏  举报