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

问题描述 投票:0回答:5

我正在编写一个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")
python python-3.x
5个回答
5
投票

使用列表的示例

import random

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

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

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


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
投票

我希望这有帮助!

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.