1 readings=[1,8,3,4,9,6,7] 2 current=readings[0] 3 defferences=[] 4 for next_item in readings[1:]:#注意next_item的值 5 defferences.append(next_item-current) 6 current=next_item 7 print(current) 8 9 for i in defferences: 10 print(i) 11 12 #辅助函数 13 def with_next(iterable): 14 ‘‘‘yield(current,next_item) tuples for each item in iterable.‘‘‘ 15 iterator =iter(iterable) 16 current=next(iterator) 17 for next_item in iterator: 18 yield current,next_item 19 current=next_item 20 21 differences=[] 22 for current,next_item in with_next(readings): 23 differences.append(next_item-current) 24 25 defferences2=[ 26 27 (next_item-current) for current,next_item in with_next(readings) 28 ]
迭代器每迭代一次就会消耗一个元素,是一次性的。所以会得到对迭代器对象求和结果为0
http://python.jobbole.com/89181/
readings=[1,8,3,4,9,6,7]current=readings[0]defferences=[]for next_item in readings[1:]:#注意next_item的值defferences.append(next_item-current) current=next_item print(current) for i in defferences: print(i) #辅助函数def with_next(iterable): ‘‘‘yield(current,next_item) tuples for each item in iterable.‘‘‘iterator =iter(iterable) current=next(iterator) for next_item in iterator: yield current,next_item current=next_item differences=[]for current,next_item in with_next(readings): differences.append(next_item-current) defferences2=[ (next_item-current) for current,next_item in with_next(readings)]
原文地址:https://www.cnblogs.com/qingsheng/p/9191623.html
时间: 2024-11-14 13:02:31