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

时间:2017-09-21 23:16:59

标签: python random

我一直试图从.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

最终结果将是(哈利和汤姆):

平均值= 0.968

有人可以帮忙吗?我一直在使用'拆分','随机导入'等等。但我并不擅长将这些放在一起。这很令人尴尬,但到目前为止我已经得到了......

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)

3 个答案:

答案 0 :(得分: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),而是更{{1}},因为即使不仅仅是两个分数,它也会起作用。

答案 1 :(得分: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 :(得分: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)