清单维护

时间:2013-11-16 01:28:02

标签: python list python-3.x

您好我正在制作一个列表维护程序,它将维护一个浮点值列表。我一直卡住了。 谁能帮我。 选项1是目前唯一可行的选项。

Option 3
Enter your choice: 3

Delete Value from List (by location in list): 2
Traceback (most recent call last):
File "C:/Python33/test 3.py", line 49, in <module>
main()
File "C:/Python33/test 3.py", line 14, in main
opt3()
File "C:/Python33/test 3.py", line 36, in opt3
list1.pop(delLocation)
TypeError: 'str' object cannot be interpreted as an integer

option 2

Enter your choice: 2

Delete Value from List (by value): 1
Traceback (most recent call last):
File "C:/Python33/test 3.py", line 49, in <module>
main()
File "C:/Python33/test 3.py", line 12, in main
opt2()
File "C:/Python33/test 3.py", line 33, in opt2
list1.remove(delValue)
ValueError: list.remove(x): x not in list

并且退出无效

我必须保持代码看起来像这样。

    list1 = [1, 2, 3, 4, 5]
def main():


    opt = -99
    while opt != 0:
      displayMenu()
      opt = intImput("\n\nEnter your choice: ")
      if opt == 1:
        opt1()
      elif opt == 2:
        opt2()
      elif opt == 3:
        opt3()
      elif opt == 4:
        opt4()
      elif opt == 0:
        print("Exiting...")
      else:
        print("Enter a valid option")

def intImput(prompt):
    try:
      return int(input(prompt))
    except:
      print("That input is incorrect")

def opt1():
    addValue=input("\nType in a value to add: ")
    list1.append(addValue)
def opt2():
    delValue=input("\nDelete Value from List (by value): ")
    list1.remove(delValue)
def opt3():
    delLocation=input("\nDelete Value from List (by location in list): ")
    list1.pop(delLocation)
def opt4():
    print(list1)
def opt0():
    print("\nExit")

def displayMenu():
    print("1.) Add Value to List\n")
    print("2.) Delete Value from List (by value)\n")
    print("3.) Delete Value from List (by location in list)\n")
    print("4.) Display List\n")
    print("\n\n0.) Exit")

main()

2 个答案:

答案 0 :(得分:4)

list1main()函数中定义,因此在其他函数中不可用。你可以

  1. list1设为全局变量(了解全局herehere)或
  2. list1作为参数传递给所有这些函数。

答案 1 :(得分:1)

在main函数中执行此操作:

global list1
list1=[1, 2, 3, 4, 5 ]