如何消除对大量if-elif-else语句的需求



我的脚本使用if-elif-else检查来确定要查看哪个数组项来创建值。问题是总共有24个elif语句,总共允许26个选项(1个用于if,1个用于错误捕获(。我想弄清楚的是如何减少elif语句的数量,从而使代码结构更好。

while choice == 0:
choice = input("Choose a block (Enter only the Number):")
if not choice.isalpha(): # Makes sure that the input is a number and not a string.
choice = int(choice)
else:
choice = 0
print("Thats not a number. Choose a number Numbnuts.")
if choice == 1:
print("n",block[0])
elif choice == 2:
print("n",block[1])
elif choice == 3:
print("n",block[2])
elif choice == 4:
print("n",block[6])
elif choice == 5:
print("n",block[7])
elif choice == 6:
print("n",block[8])
elif choice == 7:
print("n",block[3])
elif choice == 8:
print("n",block[4])
elif choice == 9:
print("n",block[5])
elif choice == 10:
print("n",block[9])
elif choice == 11:
print("n", block[10])
elif choice == 12:
print("n", block[11])
elif choice == 13:
print("n",block[12])
elif choice == 14:
print("n",block[13])
elif choice == 15:
print("n",block[14])
elif choice == 16:
print("n",block[15])
elif choice == 17:
print("n",block[16])
elif choice == 18:
print("n",block[17])
elif choice == 19:
print("n",block[18])
elif choice == 20:
print("n",block[19])
elif choice == 21:
print("n",block[20])
elif choice == 22:
print("n", block[21])
elif choice == 23:
print("n", block[22])
elif choice == 24:
print("n",block[23])
elif choice == 25:
print("n",block[24])
elif choice == 26:
print("n",block[25])

查找结构:

elif choice == 12:
print("n", block[11])
elif choice == 13:
print("n",block[12])
elif choice == 14:
print("n",block[13])
elif choice == 15:
print("n",block[14])
elif choice == 16:
print("n",block[15])

显然,这与;

print("n", block[choice - 1])

但是,对于choice in {4,5,6,7,8,9},逻辑并没有那么简单,所以您可以保留ifs:

if choice == 4:
print("n",block[6])
elif choice == 5:
print("n",block[7])
elif choice == 6:
print("n",block[8])
elif choice == 7:
print("n",block[3])
elif choice == 8:
print("n",block[4])
elif choice == 9:
print("n",block[5])
else:
print("n", block[choice - 1])

您还可以更深入:对于choice in {4,5,6},索引为choice-2,对于choice in {7,8,9},索引为choice-4:

if choice in {4,5,6}:
idx = choice - 2
elif choice in {7,8,9}:
idx = choice - 4
else:
idx = choice - 1
print("n", block[idx])

另一个答案是,寻找结构;您有不同范围的choices,它们对应于block中的不同偏移,因此您可以迭代这些:

while True:
try:
choice = input("Choose a block (Enter only the Number):")
except ValueError:
print("Thats not a number. Choose a number Numbnuts.")
continue
if choice < 1 or choice > 26:
continue
print("n")
for limit, offset in ((3, -1), (6, 2), (9, -4), (26, -1)):
if choice <= limit:
print(block[choice + offset])
break
break

因此,对于1 <= choice <= 3打印block[choice-1],对于4 <= choice <= 6打印block[choice+2],依此类推

我的版本:

block_2 = block[:3]+block[6:9]+block[3:6]+block[9:]
print("n", block_2[choice - 1])

最新更新