Fermat618's Blog

Happy coding

Python 中的 sum 函数

Fermat618 posted @ 2012年11月30日 14:54 in 未分类 , 13030 阅读
 
 

 


做 projecteuler.net 上面的题时,遇到一个问题,需要对某个范围内的数进行筛选,并且把所有符合的结果都给出来。直接些的做法是做一个数组,在筛选的时候,遇到符合条件的,就放进那个数组里面。但维护状态容易出错,我尽量避免。另一种做法就是

def foo(n):
    if p2(n):
        return [a]
    else:
        return []

然后把结果集合在一起。

集合在一起的方法在 Haskell 里面就很多了 concat, join, >>= id 等。Python 里面,我首先想到的就是用 reduce 和 + 弄了个。

from functools import reduce
from operator import add

reduce(add, map(foo, range(10000)), [])

但看着总是有些不爽。因为对于普通数的相加,一个 sum() 函数就搞定了,哪用得着那么麻烦。于是试了一下

sum(foo(x) for x in range(10000))

报错,再了看那错误信息,说是什么 int 不能和 list 相加。然后又去查了一下 sum 函数的文档

sum(iterable[, start]) -> value

Returns the sum of an iterable of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the iterable is
empty, returns start.

虽然上面写了是求数值的和,而不是字符串的,我还是试了下把最后面的那个参数置为 []

sum((foo(x)for x in range(10000)), [])

果然是可以啊。

接着我试了一下字符串的相加,得到一个有意思的错误。

sum(['foo','bar'],'')
TypeError: sum() can't sum strings [use ''.join(seq) instead]

它报了个错,然后给了个更好的写法。

''.join(seq)

用这个作为一大串字符串的相加,不但可读性好,而且效率上可以预期将比 sum() 函数的直接使用加法把字符串联接起来要好。这点在 PEP8 里面也说过,虽然 Cpython 实现的字符串的 += 运算符比较高效,但不能对其它实现作如此预期。

s = ''
for s2 in xxx:
    s += bar(s2)

的代码应该写成

''.join(bar(s2) for s2 in xxx)

 

 
scturtle 说:
2012年12月01日 19:34

filter(is_prime, xrange(1000)) 不就行了

Avatar_small
Fermat618 说:
2013年4月02日 11:09

@scturtle: 不是那个问题。是第 38 题。并不是判定某个数要不要这一件事,而是对于一个数要返回两个信息
1. 结果有没有
2. 如果有,结果是哪个

HPBOSE 11th Previous 说:
2022年8月25日 18:04

HP Board 11th Class Important Model Question Paper 2023 PDF will be Published on the Official web Portal. Himachal Pradesh 11th Class Important Model Question Paper 2023 and Marking Schemes PDF are Given Below. Important Model Question Paper 2023 are Significant Study Materials in the Exam Preparation Process. HPBOSE 11th Previous Paper 2023 Science, Geography, Sociology, Psychology, and Other Subjects Important Model Question Paper 2023 Details are Provided on This Page. for More Details About the Himachal Pradesh 11th Class Important Model Question Paper 2023 and Important Model Question Paper 2023 Kindly Visit the Official Website.

seo service UK 说:
2024年2月22日 20:58

A debt of gratitude is in order for the decent blog. It was exceptionally helpful for me. I m glad I discovered this blog. Much obliged to you for imparting to us,I too dependably gain some new useful knowledge from your post


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter