首页 > 解决方案 > 从 try-except 创建函数

问题描述

根据此答案中提供的示例,我如何从以下位置创建函数:

from collections import Counter
s =  ['0', '0', '2', '1', '1', '0', '0', '0']
try:
    print(next(t[0] for t in Counter(s).most_common(2) if t[0] != '0'))
except StopIteration:
    print('0')

此代码不起作用:

def most_common_number(s):
    try:
        return next(t[0] for t in Counter(s).most_common(2) if t[0] != '0')
    except StopIteration:
        '0'

如果有可能在不尝试的情况下获得相同的结果 - 除了请告诉我

标签: python

解决方案


您需要从except街区返回。

def most_common_number(s):
    try:
        return next(t[0] for t in Counter(s).most_common(2) if t[0] != '0')
    except StopIteration:
        return '0'

推荐阅读