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

时间:2017-04-30 12:41:11

标签: python python-3.x

我正在编写一个Python程序,我需要有一个if-else案例来选择1到9之间的数字,每个数字都分配给一个类。有关如何缩短此代码的任何建议吗?

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")

5 个答案:

答案 0 :(得分:5)

使用列表的示例

import random

classes = ['Tiefling', 'Half-Orc', 'Half-Elf', '...']

print('Your class is ' + classes[random.randrange(len(classes))])

根据亚历克西斯的评论编辑。

答案 1 :(得分:3)

使用字典的不完整版本:

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的解决方案执行相同操作):

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()

答案 2 :(得分:2)

我希望这有帮助!

import random 
classList = ['Dwarf','Elf','Halfling','Human','Dragonborn','Gnome','Half-Elf','Half-Orc','Tiefling'] 
print 'Your class is ' + random.choice(classList)

答案 3 :(得分:0)

我想你可以使用:

from random import randint
variable1 = randint(1, 9)
my_dict = {1: "Tiefling", 2: "Half-Orc", 3: "Half-Elf", 4: "Gnome", 5: "Dragonborn", 6: "Human", 7: "Halfling", 8: "Elf", 9: "Dwarf", }
base = "Your class is "
print("{}{}".format(base, my_dict[variable1]))

答案 4 :(得分:0)

如果你打算多次使用我建议你做一个功能:

def race_definer():
    races = {1: 'Tiefling', 2: 'Half-Orc', 3: 'Half-Elf', 4: 'Dragonborn',
             5: 'Elf', 6: 'Gnome', 7: 'Human', 8: 'Halfling', 9: 'Elf', 0: 'Dwarf'}

    print('Your race is {}.'.format(races[randint(0,9)]))

您可以在需要时调用该功能:

race_definer()

在使用该功能之前,不要忘记将randint导入您的程序:

from random import randint