python-3.x
2014-07-26 78 views 1 likes 
1

我已經開始學習Python的(只有前兩天),和我卡在這個代碼神交幫助 - 字典

# Enter your code for "Car colours" here. 
gr = 'Cars that are green: ' 
si = 'Cars that are silver: ' 
re = 'Cars that are red: ' 
wh = 'Cars that are white: ' 
bl = 'Cars that are blue: ' 
print(gr, si, re, wh, bl, sep = '\n') 
inp = input('Car: ') 
while inp: 
    Car = inp.split() 
    line = input('Car: ') 
    print(Car) 

我也絕對不知道從這裏到去完成代碼有如下

Car: red 
Car: white 
Car: blue 
Car: green 
Car: white 
Car: silver 
Car: 
Cars that are green: 1 
Cars that are silver: 1 
Cars that are red: 1 
Cars that are white: 2 
Cars that are blue: 1 

任何幫助,將不勝感激因爲我無法找到任何其他地方給的輸出。我正在爲GROK做這個代碼。

感謝

回答

1

它有助於使用字典:

count = {} 
while True: 
    color = input('Car: ') 
    color = color.lower() 
    if not color: 
     break 
    count.setdefault(color, 0) 
    count[color] += 1 
for color, n in count.items(): 
    print('Cars that are %s: %s' % (color, n)) 
+0

非常感謝謝謝!比我想象的要簡單得多,但做了同樣的工作! :D – user3879060

0

這個答案使用字典,僅限於已經被教導在神交教訓導致對運動的示例代碼。

car = {} 
color = input("Car: ") 

while color: 
    if color not in car: 
    car[color] = 1 
    else: 
    car[color] = car[color] + 1 
    color = input("Car: ") 
for x in car: 
    print("Cars that are", x, ":", car[x]) 
+1

解釋你的代碼是如何工作的。只有代碼答案往往被認爲是低質量的,有時會被刪除。 – Dijkgraaf

相關問題