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
yellowtail
V2EX  ›  Python

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

  •  
  •   yellowtail · 2020-10-27 14:00:33 +08:00 · 1234 次点击
    这是一个创建于 1270 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    all(f>l for f,l in zip(argv[:-1], argv[1:]))
    no1xsyzy
        4
    no1xsyzy  
       2020-10-27 15:18:19 +08:00   ❤️ 1
    不过可读性还不如 for 过一遍……
    yucongo
        5
    yucongo  
       2020-10-27 17:34:34 +08:00
    all(elm > argv[idx + 1] for idx, elm in enumerate(argv[:-1]))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3194 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:50 · PVG 18:50 · LAX 03:50 · JFK 06:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.