尽管我以前有过Java的经验,但我对Python还是很陌生。
我有以下代码将分数转换为间隔增量(作为我正在实施的“间隔重复系统”(SRS)程序的一部分)。这段代码很难看,而且可读性很差。通常,我会在Java中使用switch语句。但是在python中我找不到等效项。因此,我编写了这段代码,产生了结果。但是我想借此机会学习使用更多Python方法实现不同输出的不同选择。我将不胜感激,即使它们是我可以阅读以改进此代码的资源的指针。
<nav class="nav_menu" role="navigation">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="nav/ingredients.html">Ingredients</a>
<ul>
<li><a href="nav/fish.html">Fish</a></li>
<li><a href="nav/vegetables.html">Vegetables</a></li>
<li><a href="nav/condiments.html">Condiments</a></li>
<li><a href="nav/others.html">Others</a></li>
</ul>
</li>
<li><a href="nav/history.html">History</a></li>
<li><a href="nav/trivia.html">Trivia</a></li>
<li class="drop_btn">
<a href="#">Contact</a>
<div class="droptainer">
<h3>Sign up for the latest sushi news</h3>
<form>
<label>Name</label>
<input type="text">
<input type="text">
<label>Email</label>
<input type="text">
<input type="checkbox">
<input type="checkbox">
<label>I want to sign up for SushiNews.</label>
<button>Submit</button>
<button>Reset</button>
</form>
</div>
</li>
</ul>
</nav>
答案 0 :(得分:6)
我不会发现长的if
语句 不可读,尽管我会改用<=
来保持一致性(因为==
的情况是使用<=
已经存在的可能性。如果我是从头开始实现的,那么我可能会编写以下内容,只是为了使关联更明显:
from math import inf
SCORE_DELTAS = (
(0, +3),
(1, +2),
(3, +1),
(4, +0),
(8, -1),
(12, -2),
(20, -3),
(30, -5),
(inf, -7),
)
def score_to_delta(score):
for bound, delta in SCORE_DELTAS:
if score <= bound:
return delta
答案 1 :(得分:1)
官方的position on switch statements是,使用if语句可以很容易地执行switch语句,因此,编写长if语句是Python的方法。 PEP 275和PEP3103记录了省略switch语句的原因。实际上,尽管有多个alternatives to the switch statement.。最常见的是字典方法。
def case_a():
print('Executing case A')
def case_b():
print('Executing case B')
def case_else()
print('Executing default case')
def dict_switch(argument):
switch = {
'a': case_a
'b': case_b
}
return switch.get(argument, case_else)()
dict_switch(x)
另一种方法是将所有条件逻辑保留在一个类中,但是我发现只有在存在大量条件逻辑时才需要这样做。
class Switcher:
def numbers_to_methods_to_strings(self, argument):
"""Dispatch method"""
# prefix the method_name with 'number_' because method names
# cannot begin with an integer.
method_name = 'number_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "nothing")
# Call the method as we return it
return method()
def number_0(self):
return "zero"
def number_1(self):
return "one"
def number_2(self):
return "two"
但是,对于您而言,我认为@asthasr方法是最干净的。