Python:如何将列表添加到python中的列表列表?

时间:2014-11-23 12:33:04

标签: python

我正在学习python所以这个问题可能是一个简单的问题,我正在列表中创建汽车及其详细信息列表:

car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]),
             ("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]),
             ("3. Vauxhall Corsa STING", ["3", "53mpg", "Manual", "£8,995"]),
             ("4. VW Golf - S", ["5", "88mpg", "Manual", "£17,175"])
            ]

然后我创建了一个用于添加另一辆汽车的零件,如下所示:

new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))

它不起作用并且出现了这个错误:

Would you like to add a new car?(Y/N)Y
What is the name of the new car?test
How many doors does it have?123456
What is the fuel efficency of the new car?23456
What type of gearbox?234567
How much does the new car cost?234567
Traceback (most recent call last):
  File "/Users/JagoStrong-Wright/Documents/School Work/Computer Science/car list.py", line 35, in <module>
    car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
TypeError: string indices must be integers
>>> 

非常感谢任何人的帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

只需将元组附加到列表中,确保使用,将new_name与列表分开:

new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.append(("{}. {}".format(len(car_specs) + 1,new_name),[new_doors, new_efficency, new_gearbox, new_price]))

我会使用dict来存储数据:

car_specs = {'2. Ford Focous - Studio': ['5', '48mpg', 'Manual', '\xc2\xa317,295'], '1. Ford Fiesta - Studio': ['3', '54mpg', 'Manual', '\xc2\xa39,995'], '3. Vauxhall Corsa STING': ['3', '53mpg', 'Manual', '\xc2\xa38,995'], '4. VW Golf - S': ['5', '88mpg', 'Manual', '\xc2\xa317,175']}

然后使用以下方式添加新车

car_specs["{}. {}".format(len(car_specs)+1,new_name)] = [new_doors, new_efficency, new_gearbox, new_price]

答案 1 :(得分:-1)

您没有将第一个元素设置为正确的元组。您可以按照预期将名称附加到汽车规格的长度上。

当你执行new_name [x]时,new_name也是字符串,你要求python代表该字符串中的第x + 1个字符。

new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(str(len(car_specs + 1))+'. - ' + name, [new_doors, new_efficency, new_gearbox, new_price])