将用户输入添加到字典中

时间:2016-03-19 10:40:03

标签: python dictionary input while-loop

我在过去几个小时内一直试图这样做,但我无法正确使用代码。我想阅读用户输入(例如' red',' blue',' green',' red')并吐出颜色以及字典中该颜色的计数。

这是我的代码 - 我知道某些内容肯定是不对的,特别是在设置字典时(它还有一个while循环来连续询问输入,直到用户输入空白)

INPUT:' red',' blue',' green',' red'

after accept error 5 -1 35 Resource temporarily unavailable
socket error: Bad file descriptor

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

期望的输出

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)

我实际上甚至不确定我在上面的内容中是否需要此代码:

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您怀疑字典设置中存在的问题很少。

'dict'是python中的关键字,我建议将其作为变量名称避免使用。 Python字典通常不是订购的。不要单独使用频率和颜色名称,而是将颜色名称保存为键并计为值。

以下是包含上述更改的代码:

form.py

以下是示例测试:enter image description here

答案 1 :(得分:2)

为什么不使用比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) 更合适的数据结构?

static final int FIRST_ACTIVITY = 1;  // The request code
static final int SECOND_ACTIVITY = 2;
static final int THIRD_ACTIVITY = 3;
...
    if(first.ischecked())
        startActivityForResult(new Intent(this, FirstActivity.class));


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
if(resultCode == RESULT_OK){
    switch(requestCode){
        case FIRST_ACTIVITY:{
            //start your second activity for result
            break;
            ....
        }
    }
}

结果将是:

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 $ 格式不正确,它也是一种数据类型。 int扩展car_count = defaultdict(int),以便在自动获取之前未被访问的每个索引分配该类型的初始值。