Python:如何在Python中向列表列表添加列表?

2024-10-02 16:20:59 发布

您现在位置: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
>>> 

任何人的帮助将不胜感激,谢谢。你知道吗


Tags: ofthenamenewinputismanualcar
2条回答

您没有正确设置元组中的第一个元素。正如您所期望的,您正在将名称附加到汽车规格的长度上。你知道吗

另外,new\u name是字符串,当您执行new\u name[x]时,您会向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])

只需将元组附加到列表中,确保用,将新的\u名称与列表分开:

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]

相关问题 更多 >