【问题标题】:Adding user input to a dictionary将用户输入添加到字典
【发布时间】:2016-07-06 04:01:53
【问题描述】:

在过去的几个小时里,我一直在尝试这个,但我无法正确获取代码。我想读取用户输入(例如“红色”、“蓝色”、“绿色”、“红色”)并在字典中输出颜色和该颜色的计数。

这是我的代码 - 我知道它肯定有问题,尤其是在设置字典时(它还有一个 while 循环不断要求输入,直到用户输入空白)

输入:“红色”、“蓝色”、“绿色”、“红色”

dict = {}
car_colours = input("Car: ")
frequency = 0
  while car_colours != '':
  dict['frequency'] = car_colours.count(car_colours)
  dict['colours'] = car_colours
  frequency = frequency + 1
  car_colours = input("Car: ")
print(dict)

我还假设我需要一个 for 循环来获得下面所需的输出?

期望的输出

Cars that are red: 2
Cars that are blue: 1

我什至不确定我是否需要上面的代码:

frequency = 0
frequency = frequency + 1

感谢您的帮助!

【问题讨论】:

  • 请缩进代码 - 现在无法分辨 while lops 的结束位置。
  • 你想在字典中存储什么?您一次只能为每个 unique 键存储 一个 值。
  • 很抱歉@Wojciech Ptak 代码现在已经缩进。我想存储“颜色”,然后“频率”将是字典中的值。因此,对于每种颜色,它都会计算用户输入的次数(即频率)。
  • 尝试首先运行一个不包含循环的最小程序,只询问用户一次,将该颜色存储在字典中并打印出来。这可能有助于您了解正在发生的事情,因为 - 坦率地说 - 代码需要从头开始重写。

标签: python dictionary input while-loop


【解决方案1】:

您的字典设置中几乎没有您怀疑的问题。

'dict' 是 python 中的关键字,我建议避免将其作为变量名。 Python 字典通常不排序。不要将频率和颜色名称分开,而是将颜色名称保存为键并计数为值。

以下是上述更改的代码:

d = {}
count = 0
car_colours = raw_input("Car: ")
while car_colours != '':
    if d.has_key(car_colours):
        d[car_colours] = d[car_colours] + 1
    else:
        d[car_colours] = 1
    count = count + 1
    car_colours = raw_input("Car: ")

for k,v in d.iteritems():
    print 'Cars that are ' + k + ": " + str(v)

这里是示例测试:

【讨论】:

  • 非常感谢 Vasanth - 这看起来好多了!请问'd.has_key'是从哪里来的?
  • 这是一种检查键(颜色名称)是否已经存在的方法。如果它已经存在,则增加计数器,否则将其添加到字典中。
  • 感谢 Vasanth,有道理。我知道它在您的计算机上工作,但我的通过 Spyder 不断收到错误,但对我来说一切正常 File "", line unknown ^ SyntaxError: unexpected EOF while parsing
  • 你用的是哪个版本的python?你在哪一行得到错误?你能附上回溯吗?
  • 我使用的是 Python 2.7。我不知道如何附加回溯......但它很可能特定于我的计算机,所以所有好的 Vasanth :-) 再次感谢
【解决方案2】:

为什么不使用比dict 更合适的数据结构?

from collections import defaultdict

print "Enter car colours and ^C when done..."
try:
    car_count = defaultdict(int)
    while True:
        car_colour = raw_input("Car colour: ")
        car_count[car_colour] += 1
except KeyboardInterrupt:
    print
    print "Done with input, now the result"
    print

for c in car_count:
    print "Cars that are %s: %d" % (c, car_count[c])

结果将是:

$ python dd.py 
Enter car colours and ^C when done...
Car colour: red
Car colour: red
Car colour: green
Car colour: blue
Car colour: ^C
Done with input, now the result

Cars that are blue: 1
Cars that are green: 1
Cars that are red: 2
$

注意:即使car_count = defaultdict(int) 中的int 格式不正确,它也是一种数据类型。 defaultdict 扩展了 dict,这样之前未访问过的每个索引都会自动分配该类型的初始值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    相关资源
    最近更新 更多