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

2024-05-03 22:29:01 发布

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

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

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

为了简单起见,我只想随机选择两个分数作为开始。见下表:

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

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

平均值=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)

Tags: 文件nameimporttxtstrokerandom分数平均值
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

正如@madphestics在评论中提出的那样,不做(scores[0]+scores[1])/2,更一般的方法是sum(scores)/len(scores),因为这甚至可以用于两个以上的分数。你知道吗

假设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位来解释浮点错误。如果分数有更多的有效数字,则相应地添加更多的零。你知道吗

作为字符串传递,但可以从文件中更改它

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)

相关问题 更多 >