根据选择的#做出动作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据选择的#做出动作相关的知识,希望对你有一定的参考价值。
可以说我在底部有这个代码。如果我需要改变一些东西,它真的很烦人。编写此代码是否更容易?有阵列或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()
答案
使用字典将键映射到要运行的函数:
>>> 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)()
另一答案
您可以将函数映射到字典:
# 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()
另一答案
您可以使用类实例列表:
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())
另一答案
这是一个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
以上是关于根据选择的#做出动作的主要内容,如果未能解决你的问题,请参考以下文章
如何根据在 Kotlin 中选择的片段显示/隐藏 FloatingActionButton?