推荐学习书目
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 · 4128 views
    This topic created in 3497 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
        1
    Pythagodzilla  
       Nov 10, 2016
    print result*reduce(operator.mul, [3,2,5])
    这样?
    littleshy
        2
    littleshy  
       Nov 10, 2016   ❤️ 1
    reduce(operator.ixor,[3,2,5])
    woostundy
        3
    woostundy  
       Nov 10, 2016
    l = [3,2,5]
    reduce(lambda x,y:x^y,l)
    woostundy
        4
    woostundy  
       Nov 10, 2016
    好尴尬,刚发出来刷新发现上面有更好的写法
    zungmou
        5
    zungmou  
    OP
       Nov 10, 2016
    @Pythagodzilla
    @littleshy

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