gpt4 book ai didi

Python:从文本文件导入列表并根据多列进行排序/平均

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:46 27 4
gpt4 key购买 nike

我有一个如下所示的文本文件:

Mike 5 7 9
Terry 3 7 4
Ste 8 2 3

我写了下面的程序

  • 从文本文件中检索数据
  • 将文本分成由空格分隔的列
  • 将每个名字后面的分数按顺序排序(最低在前,最高在后)
  • 将每个人的姓名和最高分加载到列表(scoreslist)中
  • 对列表进行排序,并按字母顺序输出结果
def alphabetical():
scoreslist = []
with open ("classa.txt") as f:
content = f.read().splitlines()
for line in content:
splitline = line.split(" ")
name = splitline[0]
score = splitline[1:]
highscore = sorted(score)[-1]
scoreslist.append("{} {}".format(name,highscore))

scoreslist.sort(key=lambda x: x[0])
print(scoreslist)

最终输出如下所示:

Mike 9
Ste 8
Terry 7

我对目前的功能很满意,但我觉得它可以更简洁一些。有没有更简单的方法?

更重要的是,我想获取原始文件并使用相同的方法来创建原始文本文件中数字的平均值并以相同的格式输出。我认为可能有一个我可以使用的简单平均函数,但这显然没有发生:

score = splitline.avg[-1:-3]

最佳答案

您可以使用 statistics.mean计算你的平均值,csv lib 将文件解析成行,你永远不需要调用 read 除非你真的想要一个包含所有文件内容的字符串,你可以遍历一个文件对象并拆分每一行。

from statistics import mean
import csv

def sort_mean(fle):
with open(fle) as f:
for name, *scores in csv.reader(f, delimiter=" "):
srt = sorted(map(int, scores))
print("Highest score for {} is {}".format(name, srt[-1]))
print("Average score for {} is {}".format(name, mean(srt)))

对于您的输入文件,它将输出:

Highest score for Mike is  9
Average score for Mike is 7.0
Highest score for Terry is 7
Average score for Terry is 4.666666666666667
Highest score for Ste is 8
Average score for Ste is 4.333333333333333

现在如果你想存储所有数据并按顺序输出:

from statistics import mean
import csv
from operator import itemgetter


def sort_mean(fle):
avgs, high = [], []
with open(fle) as f:
for name, *scores in csv.reader(f, delimiter=" "):
srt = list(map(int, scores))
avgs.append((name, mean(srt)))
high.append((name, max(srt)))
avgs.sort(key=itemgetter(1), reverse=1)
high.sort(key=itemgetter(1), reverse=1)
return avgs, high

这将为您提供两个从高到低排序的列表:

In [10]: high, avgs = sort_mean("in.txt")

In [11]: high
Out[11]: [('Mike', 7.0), ('Terry', 4.666666666666667), ('Ste', 4.333333333333333)]

In [12]: avgs
Out[12]: [('Mike', 9), ('Ste', 8), ('Terry', 7)]

对于 python2,您需要自己计算平均值并且循环的逻辑略有不同:

def sort_mean(fle):
avgs, high = [], []
with open(fle) as f:
for row in csv.reader(f, delimiter=" "):
name, scores = row[0], row[1:]
srt = map(int, scores)
avgs.append((name, sum(srt,0.0) / len(srt)))
high.append((name, max(srt)))
avgs.sort(key=itemgetter(1), reverse=1)
high.sort(key=itemgetter(1), reverse=1)
return avgs, high

您可以存储用户得分最高的字典,而不是两个列表,并对存储在其中的项目进行排序。

关于你自己的功能,你可以改写如下:

def alphabetical():
scoreslist = []
with open ("classa.txt") as f:
# just iterate over the file object
# line by line
for line in f:
# don't need to pass a delimiter
split_line = line.split()
name = split_line[0]
score = split_line[1:]
# use max to get the highscore and use int as the key
# or "123" < "2"
high_score = max(score,key=int)
scores_list.append("{} {}".format(name,high_score))
# don't need lambda to sort alphabetically
scores_list.sort()
print(scores_list)

关于Python:从文本文件导入列表并根据多列进行排序/平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com