Shh*_*Shh 44 python python-2.7
这只是为了学术兴趣.我经历了很多以下情况.
either_true = False
if x:
...do something1
either_true = True
elif y:
...do something2
either_true = True
if either_true:
..do something3
Run Code Online (Sandbox Code Playgroud)
是否有任何pythonic方式,或通常更好的编程方式.基本上只有当或者elif为真时才执行something3.
Fre*_*abe 35
either_true如果doSomething3是一行代码(例如函数调用),您也可以完全省略该标志:
if x:
..do something 1
..do something 3
elif y:
..do something 2
..do something 3
Run Code Online (Sandbox Code Playgroud)
它保持评估的很好的属性x和y最多一次(而且y如果不被评估x为true).
Bak*_*riu 31
就代码重复和评估而言,您的代码几乎是最佳的.我唯一能想到避免重复的事情是:
# be optimistic!
either_true = True
if x:
do_something1
elif y:
do_something2
else:
either_true = False
if either_true:
do_something3
Run Code Online (Sandbox Code Playgroud)
这将删除一个赋值,但总行数不会更改.
优点是,这适用于n条件,无需添加任何其他任务,而您当前的解决方案需要either_true = True满足每个条件.
在我看来,它们具有相同程度的可读性,但上述代码在更多条件下会更好.
此外,没有"pythonic"方式,除了一个可读的解决方案,避免代码重复,并在效率方面是最佳的,我不知道任何类型的"更好的编程",以实现相同的结果.
Chr*_*ser 19
我会通过使用嵌套的if语句来处理这个问题
if x or y:
if x:
...do something1
elif y:
...do something2
...do something3
Run Code Online (Sandbox Code Playgroud)
正如一些评论所指出的,最佳解决方案将取决于x&y是什么.如果您的目标是易于阅读/简洁的代码,那么这个或其他答案应该没问题.然而,如果x&y是昂贵的函数调用,那么最好做一些更像你所做的事情以避免两次调用函数.
你可以在函数中包含一些:
def do_stuff():
if x:
...do something1
return True
elif y:
...do something2
return True
else:
return False
if do_stuff():
..do something3
Run Code Online (Sandbox Code Playgroud)
或者所有功能都在:
def do_stuff()
if x:
...do something1
elif y:
...do something2
else:
return
..do something3
Run Code Online (Sandbox Code Playgroud)
本着为已经提出的解决方案提供完全不同的解决方案的精神,您可以设置列表结构化词典,允许您设置绑定到预定义"事物"的多个案例
cases = [
{'condition' : x, 'action' : something1},
{'condition' : not x and y, 'action' : something2},
{'condition' : x or y, 'action' : something3},
]
for c in cases:
if c['condition']: c['action']
Run Code Online (Sandbox Code Playgroud)
我其实非常喜欢这种方法(我只是在尝试为这个问题提出一个独特的答案时才发现它,谢谢!) - 很明显哪种情况与哪种操作有关,并且很容易添加更多没有添加任何if/else语句的情况.
if x or y:
dosomethig1() if x else dosomething2()
dosomething3()
Run Code Online (Sandbox Code Playgroud)
当然,这确实评估了x.__nonzero__两次.通常这不是什么大问题,但如果它很昂贵,你可以随时评估它并将其保存为临时变量.
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |