列表理解有效但生成器表达式无效

List comprehension works but not generator expression

我正在做这道题:

Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.

我正在使用这段代码,它有效并通过了所有测试:

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        values = [n for n in arr if n if arr.count(n) == n]
        return max(values) if values else -1

但是,当我尝试将列表理解更改为生成器表达式时:

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        values = (n for n in arr if n if arr.count(n) == n)
        return max(values) if values else -1

我收到这个错误:

Traceback (most recent call last):
  File "...", line 10, in <module>
    print(Solution().findLucky([2, 3, 4]))
  File "...", line 7, in findLucky
    return max(values) if values else -1
ValueError: max() arg is an empty sequence

为什么列表理解有效而生成器表达式失败?

我试过将生成器表达式转换为理解中的列表,但这行不通,因为这样生成器就被排出了。

每个生成器都为真,因此即使生成器为“空”,您也总是调用 max(values)。正确的做法是告诉 max 然后做什么:

return max(values, default=-1)