0

我正在寻找在 python 中创建一个程序,要求用户以 [] 格式输入数字列表。

然后它必须计算并显示列表中有多少在 1 和 10、10 和 20、20 和 30 之间的数字。

10 的每个部分都将被计算,无论该部分中是否有一个数字,这意味着它可以返回 0。

这是我到目前为止所拥有的。

the_input = raw_input("Enter numbers... ") 

the_list = [int(x) for x in the_input.strip("[]").split(",")] 

group_counter = {} 

for number in the_list:
    group_start = (number // 10) * 10 
    group_end = group_start + 9 
    group_name = "%s-%s" % (group_start, group_end) 

    group_counter.setdefault(group_name, 0) 
    group_counter[group_name] += 1 

for name, count in group_counter.items():
    print "There were %s in %s" % (count, name)
4

2 回答 2

0

collections.Counter是你的朋友吗?

import collections

the_input = raw_input("Enter numbers... ") 
the_list = [int(x) for x in the_input.strip("[]").split(",")] 
group_counter = collections.Counter(x//10 for x in the_list)
bin_range = xrange(min(group_counter.keys()), max(group_counter.keys()) + 1)
for bin_tens in bin_range:
    print "There were {} in {} to {}".format(group_counter[bin_tens], bin_tens*10, bin_tens*10+9)

编辑:如果您希望打印的计数仅显示 0-9 到 90-99,则只需将 bin_range 行更改为bin_range = range(10)

于 2012-08-31T04:15:43.377 回答
0

使用您的原始格式:

the_input = raw_input("Enter numbers... ") 

the_list = [int(x) for x in the_input.strip("[]").split(",")] 

group_counter = {'0-9': 0, '10-19': 0, '20-29': 0}

for number in the_list:
    if number < 0 || number >= 30:
        continue;
    if number < 10:
        group_counter['0-9']++;
        continue;
    if number < 20:
        group_counter['10-19']++;
        continue;
    if number < 30:
        group_counter['20-29']++;
        continue;

for name, count in group_counter.items():
    print "There were %s in %s" % (count, name)
于 2012-08-31T04:23:14.957 回答