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

x in 'aeiou' and y in 'aeiou',有没有更加优雅的写法?

  •  
  •   JasonLaw · 2023-04-03 14:55:13 +08:00 · 1144 次点击
    这是一个创建于 390 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我在做Count Vowel Strings in Ranges - LeetCode,下面是我的答案。

    class Solution:
        def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
            acc_arr = list(accumulate(words, lambda acc, word: acc + (word[0] in 'aeiou' and word[-1] in 'aeiou'), initial=0))
            
            res = []
            for l, r in queries:
                res.append(acc_arr[r + 1] - acc_arr[l])
            return res
    

    我觉得 word[0] in 'aeiou' and word[-1] in 'aeiou'不够优雅,有没有好的写法?

    第 1 条附言  ·  2023-04-03 20:07:00 +08:00

    优化后的代码如下:

    class Solution:
        def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
            acc_arr = list(accumulate(words, lambda acc, word: acc + all(c in 'aeiou' for c in {word[0], word[-1]}), initial=0))
            return [acc_arr[r + 1] - acc_arr[l] for l, r in queries]
    
    5 条回复    2023-05-29 16:49:07 +08:00
    NessajCN
        1
    NessajCN  
       2023-04-03 15:07:11 +08:00
    你重点关注错了
    word[0] in 'aeiou' and word[-1] in 'aeiou' 优不优雅无所谓的,对性能没啥影响
    但是下面的 for append 不怎么优雅,建议用 list comprehension 或 map
    JasonLaw
        2
    JasonLaw  
    OP
       2023-04-03 15:33:01 +08:00 via iPhone
    @NessajCN #1 对,下面的 for loop 可以替换为 lost comprehension
    featureoverload
        3
    featureoverload  
       2023-04-03 19:11:19 +08:00
    `all([c in 'aeiou' for c in (x, y)])`
    JasonLaw
        4
    JasonLaw  
    OP
       2023-04-03 20:06:14 +08:00
    @featureoverload #3 谢谢,不过可以优化成`all(c in 'aeiou' for c in (x, y))`
    XueXianqi
        5
    XueXianqi  
       334 天前
    @featureoverload

    `all([c in 'aeiou' for c in (x, y)])`看起来优雅,但是性能考虑得不够周全
    Python 中有个叫“短路运算”的,`a and b`,如果 a 不成立,就不去运算 b 了,显然这里的 all 用得就不够优雅了
    用 all 还需要注意的是:不能完全代替 and ,比如说:
    `if a.hasattr("name") and a.name.startswith("A"):`

    这里就不能用 all ,如果 a 没有 name 这个 attribute ,就会报错。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1286 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:54 · PVG 07:54 · LAX 16:54 · JFK 19:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.