原文发于:http://qing.weibo.com/2059598087/7ac2f907330025fd.html
对于以iterable为参数的函数,可以只传入一个生成器或者迭代器,这种编程方式将最小化内存需求。
当然,如果对于传入的参数还需要进一步的使用。比如这个函数本身就是要处理一个列表,那么还是老老实实的生成这个参数较好。mixedlist = [4, 'a', 1, 2, 'n', 'u', 't', 3, 'x', 'e', 'l', 0, 'i', 'g'] def g(): for i in mixedlist: try: i+0 yield i except: pass m = max(g())
def g(): for i in mixedlist: try: i = int(i) yield i except: pass
words = ['In', 'Python,', 'string', 'objects', 'are', 'immutable.', 'Therefore,', 'any', 'operation', 'on', 'a', 'string,', 'including', 'string', 'concatenation,', 'produces', 'a', 'new', 'string', 'object,', 'rather', 'than', 'modifying', 'an', 'existing', 'one.'] def g(): for word in words: if len(word)<7: yield word result = " ".join(g())