如何在 IF 条件中分配变量,然后返回它? [英] How to assign a variable in an IF condition, and then return it?

查看:29
本文介绍了如何在 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 和在 ifwhile 中直接支持赋值的语言之间的音译.如果您在级联中拥有数百个"这样的检查和返回,那么最好做一些完全不同的事情:

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 条件中分配变量,然后返回它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆