如何从子菜单返回主菜单? 我也想将生成的数据保留在子菜单中。
主菜单:
1. Load data 2. Filter data 3. Display statistics 4. Generate plots 5. Quit
在选项2上,我有一个子菜单:
1. S. enterica 2. B. cereus 3. Listeria 4. B. thermosphacta 5. Quit
def mainMenu():
menuItems = np.array(["Load data", "Filter data", "Display statistics", "Generate plots", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria", "B. thermosphacta", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
data = data[data[:,2] == 1] # 1 - S. enterica
elif choice == 2:
data = data[data[:,2] == 2] # 2 - B. cereus
elif choice == 3:
data = data[data[:,2] == 3] # 3 - Listeria
elif choice == 4:
data = data[data[:,2] == 4] # 4 - B. thermosphacta
elif choice == 5:
return data
continue
if choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
答案 0 :(得分:0)
用以下代码替换代码:
def mainMenu():
mainMenuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
subMenuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta"])
while True:
choice = displayMenu(mainMenuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
subchoice = displayMenu(subMenuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
break
# The answer is not a correct one
continue
elif choice == 3: # instead of if
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
子菜单中不需要“退出”选项-您只想在错误答案的情况下重复嵌套循环(子菜单) (除了1,2,3或4)。
不需要执行任何操作来保存data
变量的内容,因为您执行的所有操作都在mainMenu()
函数内部。但是,如果您需要在函数之外使用它,请在任何循环之外将return data
语句用作函数中的最后。
答案 1 :(得分:0)
我在子菜单中实现了break语句,并将menuItems放入循环中。在子菜单(子选择)中完成的工作和创建的数据可以在mainMenu选项3和4中使用。
import numpy as np
from displayMenu import *
from dataLoad import *
from dataStatistics import *
from dataPlot import *
from bFilter import *
def mainMenu():
while True:
menuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta", "Back to main menu"])
subchoice = displayMenu(menuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
if subchoice == 5:
break
continue
elif choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break