Python:TypeError:list indices必须是整数或切片,而不是list

时间:2017-05-03 19:03:46

标签: python list python-3.x typeerror

好的,我现在已完全更改了我的代码,以便客户列表位于另一个列表中。现在我试图通过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 

3 个答案:

答案 0 :(得分:1)

首先使用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()

我已更新原始代码的某些部分,以使其可以运行。这段代码可以即兴创作。

答案 1 :(得分:1)

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

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('> ')  

答案 2 :(得分:0)

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

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