【问题标题】:Python: TypeError: list indices must be integers or slices, not listPython:TypeError:列表索引必须是整数或切片,而不是列表
【发布时间】:2017-10-01 18:14:57
【问题描述】:

好的,我现在已经完全更改了我的代码,以便客户列表位于另一个列表中。现在我正在尝试使用 for 循环引用每个客户的个人列表。但是当我试图访问客户列表中的单个值时,我得到了一个 TypeError:列表索引必须是整数或切片,而不是列表。代码如下:

customers = [ ]
customers.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
customers.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
customers.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
customers.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
customers.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
customers.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])



print("At Holden's Oil Change we use our custom built Python program to keep \
track of customer records \
and to display our company logo!!")
time.sleep(7)

print("Select and option from the menu!")

QUIT = '4'

COMMANDS = ('1','2','3','4')

MENU = """1   Current Customers
2   New Customers
3   Company Logo
4   Quit"""

def main():
    while True:
        print(MENU)
        command = realCommand()
        commandChoice(command)
        if command == QUIT:
            print("Program Ended")
            break

def realCommand():
    while True:
        command = input("Select an option: ")
        if not command in COMMANDS:
            print("That is not an option!")
        else:
            return command

def commandChoice(command):
    if command == '1':
        oldCust()
    elif command == '2':
        newCust()
    elif command == '3':
        Turt()

def oldCust():
    print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
    for i in customers:
        print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))

函数 oldCust() 是 for 循环运行时出现错误的地方,它给出了类型错误。我已经尝试了几种不同的方式,但每种方式都会发回相同的错误。 这是返回的整个错误:

Traceback (most recent call last):
  File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 264, in <module>
    main()
  File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 49, in main
    commandChoice(command)
  File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 66, in commandChoice
    oldCust()
  File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 79, in oldCust
    print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))
TypeError: list indices must be integers or slices, not list 

【问题讨论】:

  • 你能把代码缩减到我们真正需要查看的地方吗?
  • 我不认为你真的想把每个客户放在自己的变量中;您会发现将它们放在列表中会更好。
  • 好吧,我摆脱了所有的 newCust() 函数代码
  • 这就是我的意思斯科特。我只是想把输入的东西放进去,这样用户就可以输入多个新客户,最后我可以打印出新旧的整个列表
  • 下面的答案没有解决标题中所述的问题,是吗?我的印象是这篇文章对除了提问的人之外的任何人都不是很有用 - 反对 SE 的良好做法。

标签: python list python-3.x typeerror


【解决方案1】:

要将输入保存到多个变量,请执行以下操作:

tmp = raw_input(">>> ")
var1 = tmp
var2 = tmp
var3 = tmp

要多次使用输入,请使用函数:

def function(num):
    i = 0
    while i < num:
    tmp = raw_input(">>> ")

function(3)
var1 = tmp
var2 = tmp
var3 = tmp   

【讨论】:

    【解决方案2】:

    首先使用list 来存储客户变量。然后您可以轻松地在列表中添加新客户。

    这是您问题的完整解决方案:

    """
    Program that is used to store service
    records for prior customers or prompt
    user for customer information for new customers.
    
    The program also uses Turtle Graphics to display
    the company logo.
    """
    #Import time module for delays in program
    import time
    
    #Define current customers
    
    customer_list = []
    customer_list.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
    customer_list.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
    customer_list.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
    customer_list.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
    customer_list.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
    customer_list.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])
    
    
    #Announce the company and what our program does
    print("At Holden's Oil Change we use our custom built Python program to keep \
    track of customer records \
    and to display our company logo!!")
    time.sleep(7)
    
    #Tell the user what to do
    print("Select and option from the menu!")
    
    #Make the menu and menu options for the user
    QUIT = '4'
    
    COMMANDS = ('1','2','3','4')
    
    MENU = """1   Current Customers
    2   New Customers
    3   Company Logo
    4   Quit"""
    
    #Define how the menu works if quit option selected
    def main():
        while True:
            print(MENU)
            command = realCommand()
            commandChoice(command)
            if command == QUIT:
                print("Program Ended")
                break
    
    #Define what happens if a invalid command is entered or a correct command is entered
    def realCommand():
        while True:
            command = input("Select an option: ")
            if not command in COMMANDS:
                print("That is not an option!")
            else:
                return command
    
    #Command selection and running
    def commandChoice(command):
        if command == '1':
            oldCust()
        elif command == '2':
            newCust()
        elif command == '3':
            Turt()
    
    #Runs old customer selection
    def oldCust():
        #Print list of customers for the user to select from.
        print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
        for customer in customer_list:
            for value in customer:
                print(value,end="\t")
            print("")
    
    #Request response from user and define what happens depending on the input.
        response = input("Ener a customers last name from the list: ")
        customer_search_result = 0
        for customer in customer_list:
            if response.lower() == customer[1].lower():
                user_milage = input("Enter current vehicle mileage: ")
                user_date = input("Enter todays date (Month Day Year Format): ")
                print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
                print("%9s%13s%19s%25.9s%34s" % (customer[0], customer[1], customer[2], customer[3], customer[4]))
                print("Have a great day!")
                customer_search_result=1
    
        if customer_search_result==0:
            print("That is not a current customer!")
            time.sleep(2)
            #Request user input wheter they want to input new customer info or try another customer name.
            nonCustResponse = input("Choose 1 to re-enter customer name or 2 to enter new customer info: ")
            #if statement that decides what to do with the user input
            if nonCustResponse == "1":
                oldCust()
            elif nonCustResponse == '2':
                #Send the user to the newCust function if they enter a non-current customer
                newCust()
                #If the customer enters an invalid option the program restarts
            else:
                print("That is not an option. Program restarting")
                time.sleep(3)
    
    
    #Prompts user for information for the new customer
    def newCust():
        #Make an empty list for the new customer to be assigned to
        new_customer = [" "," "," "," "," "]
        #Request user input for the new customer information
        new_customer[0] = input("Enter the customers firsts name: ")
        new_customer[1] = input("Enter the customers last name: ")
        new_customer[2] = input("Enter the customers vehilce (Make Model): ")
        new_customer[3] = input("Enter the vehicle mileage: ")
        new_customer[4] = input("Enter today's date (Month Day Year): ")
        print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
        print("%8s%13s%22s%25s%34s" % (new_customer[0], new_customer[1], new_customer[2], new_customer[3], new_customer[4]))
        customer_list.append(new_customer)
    if __name__=='__main__':
        main()
    

    我已经更新了您原始代码的某些部分以使其能够运行。这段代码可以即兴发挥。

    【讨论】:

    • 当我对代码执行所有这些操作时,它不会将我的菜单项链接到用户输入的命令选项
    • 我已经调用了__name__中的main方法。所以,你可以照顾好这个。
    【解决方案3】:

    您可以在完成输入后允许一些转义码,即只是空字符串:

    customers = []
    new_customer = input('> ')
    while new_customer:
        customers.append(new_customer)
        new_customer = input('> ')
    

    所以当用户在没有写任何东西的情况下按下回车,输入就完成了。如果您想将“退出代码”更改为更复杂的代码,请使用:

    customers = []
    exit_code = 'stop'
    new_customer = input('> ')
    while new_customer != exit_code:
        customers.append(new_customer)
        new_customer = input('> ')  
    

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 2017-06-08
      • 2016-05-25
      • 2019-07-04
      相关资源
      最近更新 更多