V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
zungmou
V2EX  ›  Python

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

  •  
  •   zungmou · 2016-11-10 10:26:24 +08:00 · 3376 次点击
    这是一个创建于 2731 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我有一段代码,如下:
    result = 0
    for item in [3, 2, 5]:
    result ^= item
    print(result)
    以上这个 for 循环能不能用一个函数,或一个语句就计算出来?
    11 条回复    2016-11-10 14:38:29 +08:00
    Pythagodzilla
        1
    Pythagodzilla  
       2016-11-10 10:32:45 +08:00
    print result*reduce(operator.mul, [3,2,5])
    这样?
    littleshy
        2
    littleshy  
       2016-11-10 10:36:10 +08:00   ❤️ 1
    reduce(operator.ixor,[3,2,5])
    woostundy
        3
    woostundy  
       2016-11-10 10:39:25 +08:00
    l = [3,2,5]
    reduce(lambda x,y:x^y,l)
    woostundy
        4
    woostundy  
       2016-11-10 10:40:10 +08:00
    好尴尬,刚发出来刷新发现上面有更好的写法
    zungmou
        5
    zungmou  
    OP
       2016-11-10 10:43:41 +08:00
    @Pythagodzilla
    @littleshy

    reduce 在 python 3.5 没有了啊
    BBrother
        6
    BBrother  
       2016-11-10 10:46:30 +08:00
    @zungmou 你需要
    from functools import reduce
    import operator
    Herobs
        7
    Herobs  
       2016-11-10 10:47:06 +08:00 via Android
    reduce 或者递归
    Pythagodzilla
        8
    Pythagodzilla  
       2016-11-10 10:50:22 +08:00
    @zungmou 惊了,没仔细看发现写的是*...2L 是对的...
    staticor
        9
    staticor  
       2016-11-10 11:09:35 +08:00
    顺便可以了解一些函数式编程的内容
    zungmou
        10
    zungmou  
    OP
       2016-11-10 14:36:00 +08:00
    @BBrother 感谢
    @littleshy 好厉害!
    Zuckonit
        11
    Zuckonit  
       2016-11-10 14:38:29 +08:00
    reduce
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2279 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 03:42 · PVG 11:42 · LAX 20:42 · JFK 23:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.