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

查看:155
本文介绍了如何在IF条件下分配变量,然后将其返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def isBig(x):
   if x > 4: 
       return 'apple'
   else: 
       return 'orange'

这有效:

if isBig(y): return isBig(y)

这不起作用:

if fruit = isBig(y): return fruit

第二个为什么不起作用!?我要一线.除此以外,第一个将调用函数TWICE.

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

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

推荐答案

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

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)

如果在没有谓词得到满足时,None是正确的返回值,等等.

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

几乎总是使用(或什至希望;-)Holder技巧/非习惯用法是一种设计气味",这表明正在寻找一种不同的,更Python化的方法-在这种情况下,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天全站免登陆