首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用更好的条件缩短Python中的长if-else检查

使用更好的条件缩短Python中的长if-else检查
EN

Stack Overflow用户
提问于 2017-04-30 20:41:11
回答 5查看 152关注 0票数 0

我正在编写一个Python程序,其中我需要有一个if-else用例来选择1到9之间的一个数字,每个数字都被分配给一个类。关于如何使代码更短有什么建议吗?

代码语言:javascript
运行
复制
import randint

variable1 = randint(1, 9)
if variable1 >= 9:
  print ("Your class is Tiefling") 
else: 
  if variable1 >= 8: 
    print ("Your class is Half-Orc") 
  else: 
    if variable1 >= 7: 
      print ("Your class is Half-Elf") 
    else:
      if variable1 >= 6: 
        print ("Your class is Gnome")
      else:
        if variable1 >= 5:
          print ("Your class is Dragonborn") 
         else: 
           if variable1 >= 4:
            print ("Your class is Human") 
          else:
            if variable1 >= 3:
              print ("Your class is Halfling") 
            else:
              if variable1 >= 2: 
                print ("Your class is Elf") 
              else:
                if variable1 >= 1:
                  print ("Your class is Dwarf")
EN

Stack Overflow用户

发布于 2017-04-30 20:45:43

使用字典的不完整版本:

代码语言:javascript
运行
复制
val_msg = {3: 'Your class is Halfling',
           2: 'Your class is Elf',
           1: 'Your class is Dwarf'}

from random import randint

variable1 = randint(1, 3)
print(val_msg[variable1])

请注意,randint生成整数,我将其用作字典的键。

如果您需要做更复杂的事情,您可以将函数放入字典并调用它们(当然,您也可以使用此处的list-based解决方案执行相同的操作):

代码语言:javascript
运行
复制
def do_halfling_stuff():
    print('Your class is Halfling')
def do_elf_stuff():
    print('Your class is Elf')
def do_dwarf_stuff():
    print('Your class is Dwarf')

val_func = {3: do_halfling_stuff,
            2: do_elf_stuff,
            1: do_dwarf_stuff}


variable1 = randint(1, 3)
func = val_func[variable1]
func()
票数 3
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43706473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档