如何让一个程序用我的程序把年龄按年龄分组?

2024-09-29 01:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个程序,把最年轻和最年长的人写在一个.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

Tags: 文件name程序infotxt列表agemin
3条回答

一些伪代码:

要将人员附加到子组,请执行以下操作:

a_list = []

创建组

^{pr2}$

只是我愚蠢的尝试:

def parse_info(filename):
    max_age = 0
    max_name = ''
    min_age = float('inf')
    min_name = ''

    list_of_0_6 = []
    list_of_7_15 = []
    list_of_16_30 = []

    with open(filename, 'r') as info:
        lines = info.read().splitlines()
    for line in lines:
        name, age = line.split()
        age = int(age)
        if age < min_age:
            min_age = age
            min_name = name
        if age > max_age:
            max_age = age
            max_name = name
        if age < 7:
            list_of_0_6.append(line)
        elif age < 16:
            list_of_7_15.append(line)
        else:
            list_of_16_30.append(line)
    return [min_name, str(min_age), max_name, str(max_age), list_of_0_6, list_of_7_15, list_of_16_30]

def writefile(data, filename):
    with open(filename, 'w') as outputfile:
        outputfile.write(data[0] + ' ' + data[1] + '\n')
        outputfile.write(data[2] + ' ' + data[3] + '\n')
        outputfile.write('\n0-6\n')
        for entry in data[4]:
            outputfile.write(entry + '\n')
        outputfile.write('\n7-15\n')
        for entry in data[5]:
            outputfile.write(entry + '\n')
        outputfile.write('\n16-30\n')
        for entry in data[6]:
            outputfile.write(entry + '\n')

my_data = parse_info('info.txt')
writefile(my_data, 'output.txt')

最简单的方法是使用dict分组并检查分数属于哪个范围:

from collections import OrderedDict
import csv

# create dict with score ranges as keys
d = OrderedDict((("0-6", []), ("7-15", []), ("16-18", []), ("19-30", [])))

with open("match.txt") as f, open("grouped.txt", "w") as out:
    wr, read = csv.writer(out,delimiter=" "), csv.reader(f,delimiter=" ")
    mn, mx = float("inf"), float("-inf")
    highest, lowest = None, None
    for row in read:
        name, score = row
        score = int(score)
        if 0 <= score < 7:
            d["0-6"].append((name, score))
        elif 7 <= score < 16:
            d["7-15"].append((name, score))
        elif 16 <= score < 19:
            d["16-18"].append((name, score))
        elif 19 <= score <= 30:
            d["19-30"].append((name, score))
        if score < mn:
            mn = score
            lowest = (name, score)
        if score > mx:
            mx = score
            highest = (name, score)

    for k, v in d.items():
        wr.writerow([k])
        wr.writerows(v)

    print(d)

{'16-18': [], '0-6': [('George', 5)], '19-30': [('David', 20)], '7-15': [('Stacy', 11), ('Wiliam', 15), ('Annie', 8), ('Christina', 10)]}

print("Highest scorer was {} with a score of {}.".format(*highest))
print("Lowest scorer was {} with a score of {}.".format(*lowest))

Highest scorer was David with a score of 20.
Lowest scorer was George with a score of 5.

OrderedDict将保持顺序,因此我们只需要迭代dict项,写出key这是组范围和元组列表,它们是属于该范围的所有名称和分数。这个csv.reader{{2}我们只需要在cd2>范围内检查。在

相关问题 更多 >