你需要先检查一下not nums
。而且你不需要for
循环。
请注意,这(就像您的代码一样)没有明确检查max(nums) == n
,在这种情况下返回False
(我认为这应该是一个名为 的函数的正确行为gt()
):
def gt(nums, n):
if not nums:
return False
return max(nums) > n
编辑:一些时间(Python 2.7.3):
>>> import timeit
>>> all = """l = list(range(100))
... rl = list(reversed(range(100)))
... """
>>> tim = all + """def gt(nums, n):
... if not nums:
... return False
... return max(nums) > n"""
>>> gnibbler = all + """def gt(nums, n):
... return any(x>n for x in nums)"""
>>> burhan = all + """def gt(nums, n):
... return max(nums) > n if nums else False"""
>>> # Test with the condition being False:
... timeit.timeit(setup=tim, stmt="gt(l, 100)")
3.011574096311698
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
8.00847921677337
>>> timeit.timeit(setup=burhan, stmt="gt(l, 100)")
2.9805757305956178
>>> timeit.timeit(setup=tim, stmt="gt(rl, 100)")
2.8600606448831307
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
7.997938412127745
>>> timeit.timeit(setup=burhan, stmt="gt(l, 100)")
3.032805185133668
>>> # Now what if the condition is True?
... timeit.timeit(setup=tim, stmt="gt(l, 98)")
2.98623750798793
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 98)")
8.265056412191534
>>> timeit.timeit(setup=burhan, stmt="gt(l, 98)")
2.9731271156252888
>>> timeit.timeit(setup=tim, stmt="gt(rl, 98)")
2.8777295865334764
>>> timeit.timeit(setup=gnibbler, stmt="gt(rl, 98)")
1.0481696827076092
>>> timeit.timeit(setup=burhan, stmt="gt(rl, 98)")
2.8776150752220246
所以 Burhan 和我的解决方案在速度方面是相当的(这并不奇怪,因为它们做的事情完全相同,我的只是有点冗长),只有当列表足够长时,gnibbler 的速度才会明显更快(我已经删除了之前的当列表只包含 10 个项目时,它总是变慢的时间),条件评估为True
并且 搜索值在列表中很早就达到了。否则,所有 Python 级别的比较都会大大降低速度。