2014-11-23 227 views
1

我學習蟒蛇所以這個問題可能是一個簡單的問題,我在列表中創建汽車及其詳細信息的清單波紋管: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 
>>> 

任何人的幫助,將不勝感激,謝謝。

+1

你錯過了把一個逗號NEW_NAME這使得它作爲這裏的切片手術後(NEW_NAME,[new_doors,new_efficency,new_gearbox,NEW_PRICE]) – 2014-11-23 12:35:36

回答

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])) 

我會用字典來存儲數據,而不是:

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] 
+0

感謝您的幫助:) – 2014-11-24 16:14:16

-1

您沒有設置第一個元素正確地走你的元組。按照您的預期,您將名稱附加到汽車規格的長度。

而且new_name的是字符串,當你NEW_NAME [X]在該字符串的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]) 
相關問題