我有这个旧版本:
for item in items:
if not [True for key, value in items if a = b and c = d]:
if fail:
return False
else:
...
但现在我添加了更多 if 条件和作业。
for item in things:
for key, value in items:
if a == b and c == b:
sth = something
if sth in bananas:
return True
现在如何包含第一个版本中的 if failed 和 else 语句?
是否仍然可以在第二个版本(更长)中使用推导式列表? lambda 函数可能在这里有帮助,还是我必须编写一个单独的辅助函数?
由于满足条件时代码永远不会到达循环末尾
for key, value in items
,因此您可以在该循环之后立即添加 if fail: ...
代码(相同的缩进级别)。
还有一些额外的警告,但如果没有对香蕉、失败等更精确的说明,我无法告诉您可能会出现哪些其他问题(例如,当
sth
不在 bananas
中时会发生什么?)
要包含第一个版本中的 if failed 和 else 语句,您可以在内循环中使用 if 语句。例如:
for item in things:
for key, value in items:
if a == b and c == d:
sth = something
if sth in bananas:
return True
else:
return False
在这种情况下,如果 sth 的值不在香蕉列表中,则将执行 iffail 语句。否则,将执行 else 语句,函数将返回 True。
您仍然可以在代码的第二个版本中使用列表推导式。例如:
def find_bananas(things, items):
return [True for item in things
for key, value in items
if a == b and c == d and sth in bananas]
在这种情况下,lambda 函数没有帮助,因为您需要检查多个条件。