【问题标题】:Do action based on whichever # is picked根据选择的 # 执行操作
【发布时间】:2018-05-30 18:58:16
【问题描述】:
假设我在底部有这段代码。如果我需要改变一些东西,那真的很烦人。有没有更简单的方法来编写这段代码?带有数组或 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()
【问题讨论】:
标签:
python
random
numbers
action
generator
【解决方案1】:
使用字典将您的键映射到您要运行的功能:
>>> 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)()
【解决方案2】:
您可以将您的函数映射到字典:
# 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()
【解决方案3】:
您可以使用类实例列表:
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())
【解决方案4】:
这是一个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