各位,我们学校的题我是真的看不懂,有没有人可以说一下思路呀(下附我写了部分的代码)
题目:
//小朋友买了一大包气球,请写个Python程序,帮其统计不同颜色气球的个数。(选用合适的数据结构及其成员方法,方法有多种)
程序运行结果1:
请输入气球颜色,输入0结束程序:green
请输入气球颜色,输入0结束程序:red
请输入气球颜色,输入0结束程序:green
请输入气球颜色,输入0结束程序:0
不同颜色的气球数量分别为:
green:2
red:1
程序运行结果2:
请输入气球颜色,输入0结束程序:yellow
请输入气球颜色,输入0结束程序:red
请输入气球颜色,输入0结束程序:green
请输入气球颜色,输入0结束程序:blue
请输入气球颜色,输入0结束程序:0
不同颜色的气球数量分别为:
yellow:1
red:1
green:1
blue:1//
我的代码:
c=list=("")
while True:
a=list(input("请输入气球颜色,输入0结束程序:"))
if a==['0']:
break
else:
c.extend(a)
这道题需要使用Python中的字典来统计气球的颜色数量。具体思路如下:
1 初始化一个空字典,用于存储气球颜色及其数量。
2 在循环中输入气球颜色,如果输入0则退出循环,否则将颜色作为字典的键,数量为1作为字典的值存储。如果颜色已经存在于字典中,则将其数量加1。
3 循环结束后,遍历字典,输出不同颜色气球的数量。
下面是代码示例:
balloons = {}
while True:
color = input("请输入气球颜色,输入0结束程序:")
if color == '0':
break
if color not in balloons:
balloons[color] = 1
else:
balloons[color] += 1
print("不同颜色的气球数量分别为:")
for color, count in balloons.items():
print(f"{color}: {count}")
不知道你这个问题是否已经解决, 如果还没有解决的话:glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
}
word = 'string'
print("\n" + word.title() + ": " + glossary[word])
word = 'comment'
print("\n" + word.title() + ": " + glossary[word])
word = 'list'
print("\n" + word.title() + ": " + glossary[word])
word = 'loop'
print("\n" + word.title() + ": " + glossary[word])
word = 'dictionary'
print("\n" + word.title() + ": " + glossary[word])