我做了一个程序,把最年轻和最年长的人写在一个.txt列表中。在
现在我需要让程序把人和年龄分成特定的年龄组。在
[0-6], [7-15], [16-18], [19-30], [31-50], [51-)
例如,列表将是:
^{pr2}$程序应该打开一个新的.txt文件,如下所示:
0-6
Georgie 5
7-15
Annie 8
Christina 10
Stacy 11
Wiliam 15
19-30
David 20
等等,我想你们都明白我的意思了。 现在我的程序会打印出列表中最小的和最大的。在
这里是:
def parse_info():
info = open("info.txt", "r")
max_age = 0
max_name = ''
min_age = float('inf')
min_name = ''
for line in info:
m_list = line.split(" ")
if int(m_list[1]) > max_age:
max_age = int(m_list[1])
max_name = m_list[0]
elif int(m_list[1]) < min_age:
min_age = int(m_list[1])
min_name = m_list[0]
info.close()
return ((min_name,min_age),(max_name,max_age))
#end of function
nameAge=parse_info()
f = open("output.txt","w")
f.write(nameAge[0][0]+" "+str(nameAge[0][1])+"\n")
f.write(nameAge[1][0]+" "+str(nameAge[1][1]))
如何让程序先打印列表中最小的和最老的,然后再将每个人按上面给定的年龄组排序?在
程序应该这样写入.txt文件:
George 5
David 20
0-6
George 5
7-15
Annie 8
Christina 10
Stacy 11
Wiliam 15
19-30
David 20
一些伪代码:
要将人员附加到子组,请执行以下操作:
创建组
^{pr2}$只是我愚蠢的尝试:
最简单的方法是使用dict分组并检查分数属于哪个范围:
OrderedDict将保持顺序,因此我们只需要迭代dict项,写出
key
这是组范围和元组列表,它们是属于该范围的所有名称和分数。这个csv.reader{{2}我们只需要在cd2>范围内检查。在相关问题 更多 >
编程相关推荐