让我说我的代码在底部。如果我需要改变一些东西,它真的很烦人。编写此代码是否更容易?有阵列或idk的东西?我对Python很陌生,所以任何帮助都会受到赞赏。
ti = randint(1,10)
if ti == 1:
something.action()
if ti == 2:
something2.action()
if ti == 3:
something3.action()
if ti == 4:
something4.action()
if ti == 5:
something5.action()
答案 0 :(得分:0)
使用字典将您的键映射到您要运行的功能:
>>> def func1():
... print(1)
...
>>> def func2():
... print(2)
...
>>> mydict = {1: func1, 2: func2}
>>>
>>> ti = 1
>>>
>>> mydict.get(ti)()
1
>>> ti = 2
>>> mydict.get(ti)()
2
>>>
或使用您的示例:
mydict = {1: something.action, 2: something2.action}
ti = random.randint(1, 2)
mydict.get(ti)()
答案 1 :(得分:0)
您可以将函数映射到字典:
# the dictionary
# the keys are what you can anticipate your `ti` to equal
# the values are your actions (w/o the () since we don't want to call anything yet)
func_map = {
1: something.action,
2: something2.action,
3: something3.action
}
ti = randint(1, 10)
# get the function from the map
# we are using `get` to access the dict here,
# in case `ti`'s value is not represented (in which case, `func` will be None)
func = func_map.get(ti)
# now we can actually call the function w/ () (after we make sure it's not None - you could handle this case in the `else` block)
# huzzah!
if func is not None:
func()
答案 2 :(得分:0)
您可以使用类实例列表:
import random
class Something:
def __init__(self, val):
self.val = val
def action(self):
return self.val
s = [Something(i) for i in range(10)]
print(s[random.randint(1,10)-1].action())
答案 3 :(得分:0)
这是一个switch statement,这是Python本身不支持的。
上面提到的字典解决方案的映射函数是实现switch语句的好方法。你也可以使用if / elif,我发现一次性实现更容易,更易读。
if case == 1:
do something
elif case == 2:
do something else
elif case == 3:
do that other thing
else:
raise an exception