我希望在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)
答案 0 :(得分: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)
答案 1 :(得分: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)