python - 从 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'
如果有可能在不尝试的情况下获得相同的结果 - 除了请告诉我
解决方案
您需要从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'
推荐阅读
- http - Dart:未处理的异常:类型'String'不是'index'类型'int'的子类型
- rest - 使用 Genexus 的 Rest Service 问题(url 编码)
- reactjs - 与 Firestore 的实时反应聊天,我如何订阅数据?
- ruby-on-rails - 如何在没有用户会话的情况下连接 websocket?
- python - 自动更改谷歌搜索页面
- xml - XSLT:复制部分外部 XML 并更改指定元素
- php - CORS - PUT 和 DELETE 请求的问题,但只是在我的一个环境中 - 有 403 被禁止作为响应
- javascript - discord.js 试图 DM 随机人 gif
- c# - Azure 语音到文本转录不会连续运行
- c# - 当我添加文本时,C# .Net 属性(GET、SET)返回空白