Python 线性else if语句,如何将其转换为重构代码

Python 线性else if语句,如何将其转换为重构代码,python,Python,顺便说一句,anykey没有被使用 def加载1: 打印 请选择您的区域\n 1,对于区域1 \n 2,对于区域II\n 4,对于区域II\n 4,对于区域IV\n 6,对于区域VI\n 7,对于区域VI\n 7,对于区域Vi n 8,对于区域Vi \n 9,对于区域VII \n 10,对于区域IX\n的CiaGa \n的区域VII\n 11,席克斯卡根\n 11,对于区域Xi区域x \n, 选项=输入您的选项: 动作像开关 如果选项==1: 打印区域1\n csv_file=csv.reade

顺便说一句,anykey没有被使用

def加载1: 打印 请选择您的区域\n 1,对于区域1 \n 2,对于区域II\n 4,对于区域II\n 4,对于区域IV\n 6,对于区域VI\n 7,对于区域VI\n 7,对于区域Vi n 8,对于区域Vi \n 9,对于区域VII \n 10,对于区域IX\n的CiaGa \n的区域VII\n 11,席克斯卡根\n 11,对于区域Xi区域x \n, 选项=输入您的选项: 动作像开关 如果选项==1: 打印区域1\n csv_file=csv.readeropen'file/Region I.csv','r' 对于csv_文件中的行: 打印行 anykey=输入按任意键从主菜单返回 主菜单


如果希望选择的内容包含在字典中,请将函数名存储在字典中,然后调用它们:

# load(), search() and mainMenu() are defined above somewhere

def print_and_exit():
    print("Thank you for using the program.")
    exit()

def invalid_choice():
    print("Invalid choice, please select from 1 to 3")
    mainMenu()

selections={"1":load1, "2":search, "3":print_and_exit}

def select(selection):
    # call the function associated with the selection, or indicate that an invalid choice was made
    selections.get(selection, invalid_choice)()  # invalid_choice() is called if the choice is not in the selections dictionary

你的问题是什么?你想干什么?为什么你认为你需要一本字典?欢迎来到Stack Overflow!请拿着这本书,读一读。请将你的问题明确地包括在关于代码的特定问题中。在其中放一本词典是什么意思?是否希望函数使用字典?你想把这个问题的答案映射到字典上吗?还有什么吗?我想折射它。但我只是个新来的验光师我们还是不知道你的意思。具体来说,请添加有关您要解决的问题、您试图解决的问题以及这些尝试失败的原因的详细信息。要进一步清理此问题,您可以在选择中使用一个无效函数作为默认值。get.@Code Peedient done,感谢您的建议作为观察结果,此重构完全消除了对select函数的需要。别误会我的意思,这可能是最好的答案,因为OP没有发布菜单函数或调用select的任何地方。@Code学徒同意,因为它是一行,所以它可以通过使用该行而不是函数来简化,除非它在很多地方使用,在这种情况下,如果任何东西都需要重构,那么函数就更有意义了。拥有函数可以提高可重用性,这是一个很好的观点。同样,在我发表了评论之后,我意识到这个函数增加了一个抽象层次,有助于我们这些卑微的人理解它。单行程序有点迟钝,需要一些时间来破译单个selects调用更容易解析的位置。
# load(), search() and mainMenu() are defined above somewhere

def print_and_exit():
    print("Thank you for using the program.")
    exit()

def invalid_choice():
    print("Invalid choice, please select from 1 to 3")
    mainMenu()

selections={"1":load1, "2":search, "3":print_and_exit}

def select(selection):
    # call the function associated with the selection, or indicate that an invalid choice was made
    selections.get(selection, invalid_choice)()  # invalid_choice() is called if the choice is not in the selections dictionary