一些代码 I (斐波那契、for...else...、try和return、classmethod、统计个数)

2022-12-01,,,,

1. 斐波那契

from itertools import islice
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b print list(islice(fib(), 5)) # [0, 1, 1, 2, 3]

2. for……else……用法(以查找素数为例)

正常版本:

 def print_prime(n):
for i in xrange(2, n):
found = True
for j in xrange(2, i):
if i % j == 0:
found = False
break
if found:
print '%d is a prime number' %i

for……else……版本

 def print_prime(n):
for i in xrange(2, n):
for j in xrange(2, i):
if i % j == 0:
break
else:
print '%d is a prime number' % i

当循环‘自然’终结(循环条件为假)时,else从句会被执行一次,而当循环是由break语句中断时,else子句就不被执行。

与for语句相似,while语句中的else子句的语意是一样的:else块在循环正常结束和循环条件不成立时被执行。

try...except...else...finally...语句中,else在没有异常时被执行。

3. try和return

 def ReturnTest(a):
try:
if a <= 0:
raise ValueError('data can not be negative')
else:
return a
except ValueError as e:
print e
finally:
print 'the end'
return -1 print ReturnTest(0) # -1
print ReturnTest(2) #-1

ReturnTest(0)返回-1,不做解释。

ReturnTest(2)返回-1,是因为a>0,会执行else分值,但由于存在finally语句,在执行else语句的return a 语句之前会先执行finally中的语句,此时由于finally语句中有return,故程序直接返回了,所以永远不执行else语句中的return。

在实际应用程序开发过程中,并不推荐在finally中使用return语句进行返回。

4. @classmethod

 class Fruit(object):
total = 0 @classmethod
def print_total(cls):
print cls.total @classmethod
def set(cls, value):
cls.total = value class Apple(Fruit):
pass class Orange(Fruit):
pass Apple.set(200)
20 Apple.print_total() # 200 非classmethod不可这样调用,要先实例化 22
Orange.set(300)
Orange.print_total() #

普通继承是需要子类重构父类的方法。@classmethod被调用时隐形传入的参数为该对象所对应的类。

5. 统计个数

 from collections import Counter

 data = ['a', '', 2, 4, 5, '', 'b', 4, 7, 'a', 5, 'd', 'a', 'z']
print Counter(data)
# Counter({'a': 3, 4: 2, 5: 2, '2': 2, 2: 1, 'b': 1, 7: 1, 'z': 1, 'd': 1})

Counter主要用来统计散列对象,提供了3中不同的初始化方法:

 Counter('success')                         # 可迭代对象
Counter(s=3, c=2, e=1, u=1) # 关键字参数
Counter({'s':3, 'c':2, 'u':1, 'e':1}) # 字典

使用elements()方法来获取Counter中的key值

 list(Counter(data).elements())
# ['a', 'a', 'a', 2, 'b', 4, 4, 5, 5, 7, '2', '2', 'z', 'd']

使用most_common(N)方法找出前N个出现频率最高的元素以及他们对应的次数。

 Counter(data).most_common(2) # [('a', 3), (4, 2)]

当访问元素不在时,默认返回0,而不是抛出KeyError异常。

 (Counter(data))['y']    #

使用update()方法用于实现计数器对象总元素统计相加。

使用subtract()方法实现计数器对象中元素统计值相见,输入和输出的统计值允许为0或负数。

一些代码 I (斐波那契、for...else...、try和return、classmethod、统计个数)的相关教程结束。

《一些代码 I (斐波那契、for...else...、try和return、classmethod、统计个数).doc》

下载本文的Word格式文档,以方便收藏与打印。