我有这个函数定义并返回变量a
和b
,具体取决于参数orientation
的值。
def myfunc(orientation, l, w):
if orientation == 1:
a = -w
b = l
elif orientation == 2:
a = -l
b = w
elif orientation == 3:
a = -w
b = -l
elif orientation == 4:
a = -l
b = -w
elif orientation == 5:
a = w
b = l
elif orientation == 6:
a = l
b = w
elif orientation == 7:
a = w
b = -l
elif orientation == 8:
a = l
b = -w
return a, b
我的问题是:是否有更紧凑和/或更有效的方法来做同样的事情?如果有更好的方法,那是什么?
答案 0 :(得分:3)
首先,循环是不必要的;只返回最后一次迭代中分配的值。一旦你摆脱了这些,就可以很容易地看到这种模式:
def myfunc(orientation, l, w):
a, b = (w, l) if orientation % 2 else (l, w)
if orientation <= 4:
a = -a
if orientation in (3, 4, 7, 8):
b = -b
return a, b
答案 1 :(得分:1)
不太可能更快,但更简洁(并在orientation
“无效”时引发相同的例外):
def myfunc(orientation, l, w):
if 1 <= orientation <= 8:
a = (-w, -l, -w, -l, w, l, w, l)[orientation - 1]
b = (l, w, -l, -w)[(orientation - 1) % 4]
return a, b
答案 2 :(得分:1)
一种方法是使用字典。示例 -
def myfunc(orientation, l, w):
return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),
4: (-l, -w), 5: (w, l), 6: (l, w),
7: (w, -l), 8: (l, -w) }[orientation]
请注意,这将评估字典中的所有可能值,然后根据orientation
作为键选择要返回的相应值。如果希望仅在需要时评估值,则不应使用此方法。
演示 -
>>> def myfunc(orientation, l, w):
... return {1: (-w, l), 2: (-l, w), 3: (-w, -l),
... 4: (-l, -w), 5: (w, l), 6: (l, w),
... 7: (w, -l), 8: (l, -w)}[orientation]
...
>>> myfunc(3,3,4)
(-4, -3)
如果找不到密钥,上述内容将以KeyError
结尾。如果您可能使用字典中未找到的方向调用此函数,则可以使用。get(key, default)
使其返回默认的其他默认值。示例 -
def myfunc(orientation, l, w):
return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),
4: (-l, -w), 5: (w, l), 6: (l, w),
7: (w, -l), 8: (l, -w) }.get(orientation) #This returns `None` if orientation is not found in the dictionary. Use `.get(orientation, defaultval)` for some other default value.