python - 有没有办法在 Python 的 next 函数中包含多个条件?
问题描述
一般的想法是我想在每个列表中找到满足两个条件中的任何一个的第一个值。IE
a = next((x for x in the_iterable if x > 3), default_value)
但是,我希望它具有多个条件,例如:
a = next((x for x in the_iterable if x > 3 or x-1 for x in the_iterable if x>2), default_value)
我的代码现在看起来像:
a = []
for x in iterable:
if x>3:
a.append(x)
break
elif x>4:
a.append(x-1)
break
解决方案
您现在的代码更漂亮,但这会起作用:
a = next((
(x - 1 if x > 4 else x)
for x in the_iterable
if (x > 3 or x > 4)
), default_value)
推荐阅读
- flutter - 在提供程序中更改值时显示 showDialog
- java - 如何使用 Apache camel 查看来自 sqs 队列的消息?
- flask - 如何在 Flask 中的 Python 编码中添加静态路径?
- python - 函数输出 None 而不是 Return
- javascript - chrome.storage 检索值
- javascript - 从事令牌认证系统工作,有几个关于 jsonwebtoken 的问题
- ios - 想在挂起状态下杀死iOS App
- flutter - 在 Flutter 中使用 esc_pos_printer 包时无法以 Unicode 单词打印缅甸语(缅甸语)
- mysql - Next.js MySQL INSERT/UPDATE 查询似乎永远不会执行
- python - 如何仅增加字母数字值的数字值