绝地无双
您可以通过在字典中定义要执行的操作、将输入的值添加为拆分列表并为适当的输入调用适当的函数来改进:def appendit(a, *prms): v = int(prms[0]) a.append(v)def insertit(a, *prms): i = int(prms[0]) v = int(prms[1]) a.insert(i,v)def removeit(a, *prms): v = int(prms[0]) a.remove(v) # no need to testdef reverseit(a): a.reverse() def sortit(a): a.sort() def popit(a): a.pop()# define what command to run for what inputcmds = {"append_it" : appendit, "insert_it" : insertit, "remove_it" : removeit, "print_it" : print, # does not need any special function "reverse_it": reverseit, "sort_it" : sortit, "pop_it" : popit}command_list = []while True: command = input('') if command == '': break c = command.split() # split the command already # only allow commands you know into your list - they still might have the # wrong amount of params given - you should check that in the functions if c[0] in cmds: command_list.append(c)arr = []for (command, *prms) in command_list: # call the correct function with/without params if prms: cmds[command](arr, *prms) else: cmds[command](arr)输出:# inputs from user:append_it 42append_it 32append_it 52append_it 62append_it 82append_it 12append_it 22append_it 33append_it 12print_it # 1st printoutsort_itprint_it # 2nd printout sortedreverse_itprint_it # 3rd printout reversed sortedpop_it print_it # one elem poppedinsert_it 4 99remove_it 42print_it # 99 inserted and 42 removed# print_it - outputs[42, 32, 52, 62, 82, 12, 22, 33, 12][12, 12, 22, 32, 33, 42, 52, 62, 82][82, 62, 52, 42, 33, 32, 22, 12, 12][82, 62, 52, 42, 33, 32, 22, 12][82, 62, 52, 99, 33, 32, 22, 12]