好的,我现在已完全更改了我的代码,以便客户列表位于另一个列表中 . 现在我试图通过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 回答
首先使用
list
来存储客户变量 . 然后,您可以轻松地在列表中添加新客户 .以下是您问题的完整解决方案:
我已更新原始代码的某些部分,以使其可以运行 . 此代码可以即兴创作 .
完成输入后,您可以允许一些转义码,即只是空字符串:
因此,当用户在没有写任何内容的情况下点击输入时,输入就完成了 . 如果您想将“退出代码”更改为更复杂的内容,请使用以下命令:
要将输入保存到多个变量,请执行以下操作:
要多次使用输入,请使用以下函数: