从 .txt 文件中随机选择分数并计算它们的平均值(Python)

3

我一直在尝试从一个 .txt 文件中随机选择分数,然后找到这些随机选定分数的平均值。下面是一个示例:

James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964

为了简单起见,我只想随机选择2个分数开始。请参见下面:

James, 0.974
Harry, 0.971 <---
Ben, 0.968
Tom, 0.965 <---
George, 0.964

最终结果将是(Harry和Tom):
平均值 = 0.968
有人能帮忙吗?我一直在使用'split','import random'等,但我不擅长把它们结合起来。这很尴尬,但这是我目前为止的成果...
import random

stroke = random.choice(open('stroke.txt').readlines()) 
for x in stroke:
    name, score = stroke.split(',')
    score = int(score)
    stroke.append((name, score))
print(stroke)

2
使用 splitimport random 等是很好的开始,你能分享一下你已经开始的代码吗?这样我们就可以知道你卡在哪里了。如果可以,请点击问题下面的 [edit] 按钮,并将您的代码作为文本添加(选择,然后使用 {} 按钮格式化您的代码),谢谢。 - chickity china chinese chicken
谢谢回复,我已经按照你的要求完成了。希望有所帮助(但我觉得可能不会,抱歉!) - Eddie Henry
代码确实是一个非常好的开始。你能解释一下你得到了什么输出,包括任何错误,并告诉我那与你想要/期望的有什么不同吗? - Mad Physicist
3个回答

3
尝试使用以下代码(对代码进行解释):
import random

# read the file in lines
with open('file.txt','r') as f:
    lines = f.read().splitlines()

# split in ',' and get the scores as float numbers 
scores = [ float(i.split(',')[1]) for i in lines]

# get two random numbers
rs = random.sample(scores, 2)

# compute the average
avg = sum(rs)/len(rs)
print avg

现在,如果您想修改您的代码,可以按照以下步骤进行操作:
import random

# pick two instead of one
stroke = random.sample(open('file.txt').readlines(),2) 

scores = []
for x in stroke:
    # split item of list not the list itself
    name, score = x.split(',')
    # store the two scores on the scores list
    scores.append(float(score))

print (scores[0]+scores[1])/2

在评论中,@MadPhysicist提出,不要使用(scores[0]+scores[1])/2的方式,更通用的方式是使用sum(scores)/len(scores),因为这种方式即使对于超过两个分数也适用。


在求平均数的第二个版本中,您可能想使用加号+而不是斜杆/。 - Mad Physicist
sum(scores)/len(scores) 更为通用。原帖提到2只是一个例子。 - Mad Physicist
@MadPhysicist 是的,谢谢!我甚至没有注意到那个 :) - coder
@MadPhysicist 是的,好主意!我会更新的,使用 sum 更加优雅! - coder
大家好,非常感谢! - Eddie Henry
显示剩余3条评论

0
假设 scores.txt 文件格式如下:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964

那么这应该就可以解决问题了:

import random

scores = open('scores.txt','r').read()
scores = scores.split('\n')

for i in range(len(scores)):
    scores[i] = scores[i].split(', ')
    scores[i][1] = float(scores[i][1]) * 1000

def rand_avg_scores(scorelist):
    score1 = scorelist.pop(random.randint(0,len(scorelist)-1))
    score2 = scorelist.pop(random.randint(0,len(scorelist)-1))

    finalscore = (score1[1] + score2[1])/2000

    return score1[0], score2[0], finalscore

print(rand_avg_scores(scores))

我添加了* 1000/2000位,以解决浮点错误的问题。如果分数有更多有效数字,请相应地添加更多的零。


这个程序硬编码了2个分数。Op明确提到2只是一个例子,即不应该硬编码。 - Mad Physicist
1000和2000位不会按照你想象的方式工作,特别是考虑到浮点数可以处理的约15个小数位。 - Mad Physicist
非常感谢!我一直在调整和添加自己的东西到这段代码中,这真是太有趣了!再次感谢 :) - Eddie Henry

0

以字符串形式传递,但可以从文件中更改

import random

scoresString = '''
James, 0.974

Harry, 0.971

Ben, 0.968

Tom, 0.965

George, 0.964
'''

# How much randoms
randomCount = 2

# Get lines of the pure string
linesPure = scoresString.split("\n")

# Get lines that have content
rowsContent = [line for line in linesPure if(line.strip())]

# Get random lines
chosenRows = random.sample(rowsContent, randomCount)

# Sum of chosen
sum = 0

for crow in chosenRows:
    sum += float(crow.split(",")[1].strip())

# Calculate average
average = sum / len(chosenRows)

print("Average: %0.3f" % average)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接