如何使这个elif语句更有效率

时间:2016-02-19 16:22:28

标签: python

future=random.randint(1,8)

if future == 1:
         answer = option1
elif future == 2:
         answer = option2
elif future == 3:
         answer = option3
elif future == 4:
         answer = option4
elif future == 5:
         answer = option5
elif future == 6:
         answer = option6
elif future == 7:
         answer = option7
else:
         answer = option8

我需要缩短/提高效率,任何帮助都会很棒,谢谢:)

2 个答案:

答案 0 :(得分:5)

为什么不将选项存储在列表中?

...
<li>
    <h4>Plain Modal</h4>
    <Button label="Modal Dialog" onClick={ this.handleOpen } />
    <Modal
        open={ this.state.open }
        handleClose={ this.handleClose }
        handleOpen={ this.handleOpen } />
</li>
...

答案 1 :(得分:4)

为什么不使用字典:

import random
future=random.randint(1,8)

answer_dict = {1: option1, 2: option2, 3: option3, 4: option4, 5: option5, 6: option6 ,7: option7}
answer = answer_dict.get(future, option8)