推荐学习书目
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
yellowtail
V2EX  ›  Python

函数可变参数遇到固定语句无法判断参数关系的问题

  •  
  •   yellowtail · Oct 27, 2020 · 1823 views
    This topic created in 2029 days ago, the information mentioned may be changed or developed.

    比如有两个可变参数,ab,需要比较参数关系是否符合 a>b,可以写 if argv[0]>argv[1]: 但是现在有三个参数 abc 的话,需要比较是否 a>b>c,问题就来了。。之前判断式是为两个参数准备的,只能再加一个判断,然后根据参数数量选择执行方式。。如果参数多了该怎么办呢?有什么好的解决办法?

    5 replies    2020-10-27 17:34:34 +08:00
    yellowtail
        1
    yellowtail  
    OP
       Oct 27, 2020
    又思考了下,可以用 for 循环进行多次判断。。不过感觉有点取巧,不知道是否有更普适的方法。。
    xiaolinjia
        2
    xiaolinjia  
       Oct 27, 2020   ❤️ 1
    if sorted(argv, reverse=True) == list(argv):
    嫌麻烦可以这样一句,不过效率比较低,元素多了就不够好。
    no1xsyzy
        3
    no1xsyzy  
       Oct 27, 2020
    是指任意参数表以降序排列吗?

    all(f>l for f,l in zip(argv[:-1], argv[1:]))
    no1xsyzy
        4
    no1xsyzy  
       Oct 27, 2020   ❤️ 1
    不过可读性还不如 for 过一遍……
    yucongo
        5
    yucongo  
       Oct 27, 2020
    all(elm > argv[idx + 1] for idx, elm in enumerate(argv[:-1]))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1118 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 18:18 · PVG 02:18 · LAX 11:18 · JFK 14:18
    ♥ Do have faith in what you're doing.