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

Shortening a long if-else check in Python using better conditions

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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")


使用列表的示例

1
2
3
4
5
import random

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

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

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


使用字典的不完整版本:

1
2
3
4
5
6
7
8
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的解决方案):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()


希望这有帮助!

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

如果您要多次使用此功能,我建议您使用以下功能:

1
2
3
4
5
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)]))

在需要的时候调用函数:

1
race_definer()

在使用函数之前,请不要忘记将randint导入程序:

1
from random import randint

我想你可以用:

1
2
3
4
5
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]))