简体   繁体   English

如何计算文本文件中每个人的平均人数

[英]how to calculate average number of each person in a text file

Hi i want to create a code that read a text file and print the average of each person in the file, i have this in the folder嗨,我想创建一个读取文本文件并打印文件中每个人的平均值的代码,我在文件夹中有这个

boys.txt

ed lin,3,1,4,2
thomas block,6,3,3
Functions.py

def read_txt(file_txt):
    file = open(file_txt, "r")
    lines = file.readlines()
    file.close()
    return lines
from Functions import read_txt

file_txt = input("input file: ")
read_txt(file_txt)

lines = (sum(lines)/len(lines))

print(lines)

so i want to print something like所以我想打印类似的东西

ed lin: 2.5
thomas block: 4

but i dont know how to continue and with my code i get error但我不知道如何继续,我的代码出现错误

Try changing your other file to:尝试将您的其他文件更改为:

from Functions import read_txt

file_txt = input("input file: ")
lines read_txt(file_txt)

lines = '\n'.join(['%s: %s' % (line.split(',')[0], sum(list(map(int, line.strip().split(',')[1:]))) / len(line.strip().split(',')[1:])) for line in lines])

print(lines)

Output: Output:

ed lin: 2.5
thomas block: 4

I don't know why you are not allowed to use format, but without using it, it would be a little too tedious... In the meantime, here is another way you can do.我不知道为什么不允许您使用格式,但是如果不使用它,那将有点太乏味了...同时,您可以使用另一种方法。

with open("boys.txt", "r") as f:
    contents = f.read()

lines = contents.strip().split("\n")

for l in lines:
    boy = l.split(",")
    length = len(boy)
    score = 0
    for i in range(1, length):
         score += int(boy[i])
    average = score / (length-1)
    print("{}: {}".format(boy[0], average))

You could also use你也可以使用

from Functions import read_txt

file_txt = input("input file: ")
with open(file_txt, 'r') as f:
  lines = f.readlines()
  for line in lines:
    name = line[0: line.index(',')]
    data = [int(num) for num in (line[line.index(',')+1:].split(','))] 
    nums = len(data)
    data = sum(data)
    print(f"{name}: {data/nums}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM