from itertools import *# Easy joining of two lists into a list of tuplesfor i in izip([1, 2, 3], [ a , b , c ]): print i# ( a , 1)# ( b , 2)# ( c , 3)# The count() function returns an interator that # produces consecutive integers, forever. This # one is great for adding indices next to your list # elements for readability and conveniencefor i in izip(count(1), [ Bob , Emily , Joe ]): print i# (1, Bob )# (2, Emily )# (3, Joe ) # The dropwhile() function returns an iterator that returns # all the elements of the input which come after a certain # condition becomes false for the first time. defcheck_for_drop(x):print Checking: , x return (x > 5)for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]): print Result: , i# Checking: 2# Checking: 4# Result: 6# Result: 8# Result: 10# Result: 12# The groupby() function is great for retrieving bunches# of iterator elements which are the same or have similar # propertiesa = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])for key, value in groupby(a): print(key, value), end=)# (1, [1, 1, 1])# (2, [2, 2, 2]) # (3, [3, 3]) # (4, [4]) # (5, [5])
Generator 函数
Generator 函数是一个类似迭代器的函数,即它也可以用在 for 循环语句中。这大大简化了你的代码,而且相比简单的 for 循环,它节省了很多内存。
比如,我们想把 1 到 1000 的所有数字相加,以下代码块的第一部分向你展示了如何使用 for 循环来进行这一计算。
如果列表很小,比如 1000 行,计算所需的内存还行。但如果列表巨长,比如十亿浮点数,这样做就会出现问题了。使用这种 for 循环,内存中将出现大量列表,但不是每个人都有无限的 RAM 来存储这么多东西的。Python 中的 range() 函数也是这么干的,它在内存中构建列表。
也就是说,如果你想对列表进行多次迭代,并且它足够小,可以放进内存,那最好使用 for 循环或 Python 2.x 中的 range 函数。因为 generator 函数和 xrange 函数将会在你每次访问它们时生成新的列表值,而 Python 2.x range 函数是静态的列表,而且整数已经置于内存中,以便快速访问。
# (1) Using a for loopvnumbers = list()for i in range(1000): numbers.append(i+1)total = sum(numbers)# (2) Using a generatordefgenerate_numbers(n): num, numbers = 1, [] while num < n: numbers.append(num) num += 1return numbers total = sum(generate_numbers(1000)) # (3) range() vs xrange() total = sum(range(1000 + 1)) total = sum(xrange(1000 + 1))
评论