如何在 IF 条件中分配变量,然后返回它?

编程入门 行业动态 更新时间:2024-10-23 17:37:07
本文介绍了如何在 IF 条件中分配变量,然后返回它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 def isBig(x): if x > 4: return 'apple' else: return 'orange'

这有效:

if isBig(y): return isBig(y)

这不起作用:

if fruit = isBig(y): return fruit

为什么第二个不起作用!?我想要一个 1-liner.除了,第一个将调用函数 TWICE.

Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.

如何在不调用函数两次的情况下使其成为 1 个 liner?

推荐答案

我看到其他人已经指出了我旧的分配和设置"食谱,其最简单的版本归结为:

I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:

class Holder(object): def set(self, value): self.value = value return value def get(self): return self.value h = Holder() ... if h.set(isBig(y)): return h.get()

然而,这主要是为了简化 Python 和在 if 或 while 中直接支持赋值的语言之间的音译.如果您在级联中拥有数百个"这样的检查和返回,那么最好做一些完全不同的事情:

However, this was intended mostly to ease transliteration between Python and languages where assignment is directly supported in if or while. If you have "hundreds" of such check-and-return in a cascade, it's much better to do something completely different:

hundreds = isBig, isSmall, isJuicy, isBlah, ... for predicate in hundreds: result = predicate(y) if result: return result

甚至类似的东西

return next(x for x in (f(y) for f in hundreds) if x)

如果不满足谓词则可以得到 StopIteration 异常,或者

if it's OK to get a StopIteration exception if no predicate is satisfied, or

return next((x for x in (f(y) for f in hundreds) if x)), None)

if None 是不满足谓词时的正确返回值,等等.

if None is the proper return value when no predicate is satisfied, etc.

几乎总是使用(或什至希望;-)Holder 技巧/非习语是一种设计味道",这表明寻找一种不同的、更 Pythonic 的方法——一个案例Holder 被证明是正确的正是我设计它的特殊情况,即,您希望在 Python 代码和一些非 Python 代码之间保持密切对应的情况(您正在音译参考算法在 Python 中,并希望它在将其重构为更 Pythonic 的形式之前先运行,或者您正在编写 Python 作为原型,一旦它有效工作,它将被音译为 C++、C#、Java 等).

Almost invariably, using (or even wishing for;-) the Holder trick/non-idiom is a "design smell" which suggests looking for a different and more Pythonic approach -- the one case where Holder is justified is exactly the special case for which I designed it, i.e., the case where you want to keep close correspondence between the Python code and some non-Python (you're transliterating a reference algorithm in Python and want it working first before refactoring it into a more Pythonic form, or you're writing Python as a prototype that will be transliterated into C++, C#, Java, etc, once it's working effectively).

更多推荐

如何在 IF 条件中分配变量,然后返回它?

本文发布于:2023-10-27 03:25:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532176.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   分配   条件   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!