【问题标题】:Python 2.7, smart conditioningPython 2.7,智能调节
【发布时间】:2018-05-07 10:53:31
【问题描述】:

这是我的情况:我得到布尔值 ab 并且我有函数 eatAB() 可以吃 a 或 b 或不吃。

这是我的问题:eatAB() 必须被调用一次,我希望它“聪明又漂亮”。我可以这样做:

if not a and not b:
    eatAB()
elif a and not b:
    eatAB(a=a)
elif not a and b:
    eatAB(b=b)
else:
    eatAB(a,b)

但对我来说,这个有点烂)有没有更漂亮、更好、更聪明或其他方式来做到这一点?感谢您的时间。

【问题讨论】:

  • 你的函数是如何“吃掉”布尔值的?显示eatAB 的代码和您想要的最终输出。这可能是这个逻辑可以更整齐地进入函数
  • 我假设因为您很乐意在所有情况下使用相同的函数,所以它会检查 a 或 b 是否为 None 来执行它的逻辑。如果是这样,请将它们作为eatAB(a if a else None, b if b else None) 传递并摆脱所有条件。
  • @Bilkokuya if 检查也可以在函数内部移动

标签: python algorithm python-2.7 structure pretty-print


【解决方案1】:

这篇文章分为两部分,顶部是基于 OP 的新信息的更新答案 - 关于 eatAB() 不允许或不能修改。第二个答案是如果您有权修改函数本身,您将如何解决这个问题的原始答案。


更新的答案(您缺乏修改功能的访问/权限)

由于您无权在内部更改函数,但您知道它的签名 eatAB(a=None,b=None) 我们希望遵循此逻辑(来自问题):

  • 如果我们传入的值是真实的(例如True),我们想要传递该值
  • 如果该值不为真,我们希望使用参数的默认值,即None

这可以使用以下表达式轻松完成:

value if condition else otherValue

在调用函数时使用它会给出以下结果:

a = False
b = True
eatAB(a if a else None, b if b else None)
# will be the same as calling eatAB(None, True) or eatAB(b=True)

当然,如果 a 和 b 的值来自条件本身,您可以直接使用该条件。例如:

eatAB(someValue if "a" in myDictionary else None, someOtherValue if "b" in myDictionary else None)

原始答案(您有权修改函数)

不知道eatAB() 到底是做什么的或它的确切签名,我可以推荐的最好的方法如下。我相信您可以根据需要进行调整。

主要思想是将逻辑移至eatAB(),因为它是函数的职责,而不是调用代码。解释在 cmets 中:

# for parameters a and b to be optional as you have shown, they must have a default value
# While it's standard to use None to denote the parameter is optional, the use case shown in the question has default values where a or b are False - so we will use that here.
def eatAB(a=False, b=False):
    # check if the parameters are truthy (e.g. True), in which case you would have passed them in as shown in the question.
    if a:
        # do some logic here for when a was a truthy value
    if b:
        # do some logic here for when b was a truthy value
    # what exactly the eatAB function I cannot guess, but using this setup you will have the same logic as wanted in the question - without the confusing conditional block each time you call it.

# function can then be called easily, there is no need for checking parameters
eatAB(someValue, someOtherValue)

感谢 Chris_Rands 的改进建议。

【讨论】:

  • 嘿,我想我需要提供更多细节:
  • 实际任务是这样的:我们有字典dictionary = {},它可能包含也可能不包含键'a'或'b'。我们不允许在其中修改 'eatAB()' 函数 'eatAB()' 是这样的:'eatAB(a=None, b=None): ....'。并且 'eatAB()' 采用 "dictionary['a']" 和 "dictionary['b']" 的值,我们必须确保它不会引发 KeyError 并且不需要调用eatAB()不止一次。所以问题是检查字典中的键 a 或 b,然后将其传递到eatAB() 中。很抱歉之前没有显示完整的问题,思想可以使其仅与布尔值一起使用。谢谢
  • @ChynaJake 以后,请澄清问题中的所有限制 - 否则您会浪费回答者的时间和精力来提供帮助。我已更新答案以包含您添加的新信息。
猜你喜欢
  • 2018-09-23
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 2010-10-28
  • 2019-11-11
  • 2022-10-23
相关资源
最近更新 更多