Python 遍历一个数组并计算最终结果

2016 年 11 月 10 日
 zungmou
我有一段代码,如下:
result = 0
for item in [3, 2, 5]:
result ^= item
print(result)
以上这个 for 循环能不能用一个函数,或一个语句就计算出来?
4325 次点击
所在节点    Python
11 条回复
Pythagodzilla
2016 年 11 月 10 日
print result*reduce(operator.mul, [3,2,5])
这样?
littleshy
2016 年 11 月 10 日
reduce(operator.ixor,[3,2,5])
woostundy
2016 年 11 月 10 日
l = [3,2,5]
reduce(lambda x,y:x^y,l)
woostundy
2016 年 11 月 10 日
好尴尬,刚发出来刷新发现上面有更好的写法
zungmou
2016 年 11 月 10 日
@Pythagodzilla
@littleshy

reduce 在 python 3.5 没有了啊
BBrother
2016 年 11 月 10 日
@zungmou 你需要
from functools import reduce
import operator
Herobs
2016 年 11 月 10 日
reduce 或者递归
Pythagodzilla
2016 年 11 月 10 日
@zungmou 惊了,没仔细看发现写的是*...2L 是对的...
staticor
2016 年 11 月 10 日
顺便可以了解一些函数式编程的内容
zungmou
2016 年 11 月 10 日
@BBrother 感谢
@littleshy 好厉害!
Zuckonit
2016 年 11 月 10 日
reduce

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/319465

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX