Q:
You are curious about the most popular and least popular colours of cars and decide to write a program to calculate the frequency of car colours.
Your program should read in the colour of each car until a blank line is entered, and then print out (in any order) all the different colours of car with counts.
For example:
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
Here is another example:
Car: red
Car: white
Car: white
Car: red
Car: white
Car: white
Car: white
Car:
Cars that are red: 2
Cars that are white: 5
A:
dic_colour1 = {}
dic_colour2 = {}
colour = []
car_colour = input("Car: ")
while car_colour:
colour.append(car_colour)
colour_num = colour.count(car_colour)
car_sentence = "Cars that are " + car_colour+":"
dic_colour1[car_sentence] = colour_num
dic_colour2.update(dic_colour1)
car_colour = input("Car: ")
for element in dic_colour2:
print(element, dic_colour2[element])
- list.append()
- list.count()
- create dictionaries in while loop
- dictionary.update()
本文介绍了一个简单的程序,用于统计输入的汽车颜色频率。程序读取每辆汽车的颜色,直到输入空白行为止,然后输出所有不同颜色汽车的数量。通过创建字典来跟踪每种颜色的出现次数,最后打印出每种颜色及其对应的计数。
3763

被折叠的 条评论
为什么被折叠?



