Python编程技巧之Iterable参数

原文发于: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())


当然,如果要把其中能转换为数字的字符串也算上的话,其中的g()可改写为:
def g():
    for i in mixedlist:
        try:
            i = int(i)
            yield i
        except:
            pass


或者你只需要将长度小于7的字符串用空格串起来:
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())


采用列表解析方式(即先列表解析生成结果列表,再调用join函数)耗时为上述方式的80%(words长度为2710000)或74%(words长度为8130000)。这多余的时间消耗,可能与程序切换有关。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值