for
for和else的使用,当for正常的走完不是因为break走完时会执行else否则不会执行else 例如下面的寻找素数的方法
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print n,'equals',x,'*',n/x
break
else:
print n, 'is a prime number'
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your {0}? It is {1}.'.format(q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
try
try和else 当try的语句块没有异常的时候try搭配的else会执行否则不会执行
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
函数参数
在函数参数中可以使用*name 和**name 其中*name可以包含一个tuple **name包含一个字典 确保*name要在**name前面 如果两个都存在的话 样例
def cheeseshop(kind, *arguments, **keywords):
print kind
for arg in arguments:
print arg
for kw in keywords:
print kw,":",keywords[kw]
cheeseshop("cx","aa","bb",3,name="cx",school="fafu",age=26)
aa=["aa","bb",3]
aaa={name:"cx",school="fafu",age=26}
cheeseshop('cx',*aa,**aaa)
filter 过滤数据
数据满足函数条件返回True的时候符合条件 If sequence is a str, unicode or tuple, the result will be of the same type,otherwise, it is always a list. 如果序列是str unicode,tuple 返回的是相同的类型否则就是list类型
def f(x): return x % 3 == 0 or x % 5 == 0
print filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
def c(x):return x>'b'
b = 'abbcaabbcc'
print filter(c,b)
ccc
map
def cube(x): return x*x*x
print map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
seq = range(8)
def add(x, y): return x+y
map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
reduce
返回 计算在序列的前两项.调用二元函数函数构造的单个值,然后接下来都是结果和下一项被函数调用,依此类推。 例如,计算数字1到10的总和
def add(x,y): return x+y
reduce(add, range(1, 11))
// 如果只有一个值 就返回一个值,如果为空返回异常,使用三个参数第三个参数作为第一个值,即使为空也不返回错误
def sum(seq):
def add(x,y): return x+y
return reduce(add, seq, 0)
print sum(range(1, 11))
55
print sum([])
0
list
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
等价于
squares = [x**2 for x in range(10)]
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
等价于
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]