推荐学习书目
› 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 · Nov 10, 2016 · 4406 views
    This topic created in 3648 days ago, the information mentioned may be changed or developed.
    我有一段代码,如下:
    result = 0
    for item in [3, 2, 5]:
    result ^= item
    print(result)
    以上这个 for 循环能不能用一个函数,或一个语句就计算出来?
    11 replies  •  2016-11-10 14:38:29 +08:00
    Pythagodzilla
    Pythagodzilla
    Nov 10, 2016
    1
    print result*reduce(operator.mul, [3,2,5])
    这样?
    littleshy
    littleshy
    Nov 10, 2016❤️1
    2
    reduce(operator.ixor,[3,2,5])
    woostundy
    woostundy
    Nov 10, 2016
    3
    l = [3,2,5]
    reduce(lambda x,y:x^y,l)
    woostundy
    woostundy
    Nov 10, 2016
    4
    好尴尬,刚发出来刷新发现上面有更好的写法
    zungmou
    zungmou
    OP
    Nov 10, 2016
    5
    @Pythagodzilla
    @littleshy

    reduce 在 python 3.5 没有了啊
    BBrother
    BBrother
    Nov 10, 2016
    6
    @zungmou 你需要
    from functools import reduce
    import operator
    Herobs
    Herobs
    Nov 10, 2016 via Android
    7
    reduce 或者递归
    Pythagodzilla
    Pythagodzilla
    Nov 10, 2016
    8
    @zungmou 惊了,没仔细看发现写的是*...2L 是对的...
    staticor
    staticor
    Nov 10, 2016
    9
    顺便可以了解一些函数式编程的内容
    zungmou
    zungmou
    OP
    Nov 10, 2016
    10
    @BBrother 感谢
    @littleshy 好厉害!
    Zuckonit
    Zuckonit
    Nov 10, 2016
    11
    reduce
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4816 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 08:37 · PVG 16:37 · LAX 00:37 · JFK 03:37
    ♥ Do have faith in what you're doing.