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

2023-04-03 14:55:13 +08:00
 JasonLaw

我在做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'不够优雅,有没有好的写法?

1156 次点击
所在节点    Python
5 条回复
NessajCN
2023-04-03 15:07:11 +08:00
你重点关注错了
word[0] in 'aeiou' and word[-1] in 'aeiou' 优不优雅无所谓的,对性能没啥影响
但是下面的 for append 不怎么优雅,建议用 list comprehension 或 map
JasonLaw
2023-04-03 15:33:01 +08:00
@NessajCN #1 对,下面的 for loop 可以替换为 lost comprehension
featureoverload
2023-04-03 19:11:19 +08:00
`all([c in 'aeiou' for c in (x, y)])`
JasonLaw
2023-04-03 20:06:14 +08:00
@featureoverload #3 谢谢,不过可以优化成`all(c in 'aeiou' for c in (x, y))`
XueXianqi
348 天前
@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 ,就会报错。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/929428

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX