读取文件并在Python中计算内容的平均值

huangapple go评论69阅读模式
英文:

Reading files and averaging the contents in Python

问题

我正在阅读三个不同的文件并打印输出。然而,我还想打印出这三个文件中每一行的平均值。我展示当前的输出和期望的输出。

当前的输出是

1
2
3

4
5
6

7
8
9

期望的输出是

4 #(1+4+7)/3
5 #(2+5+8)/3
6 #(3+6+9)/3
英文:

I am reading three different files and printing the output. However, I also want to print the average of each line from the three files. I present the current and expected outputs.

N = [1, 2, 3]
for i in N:
    filepath = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Trials\{}\len_J.py".format(i)
    try:
        with open(filepath, "r") as f:
            content = f.read()
            print(content)
    except FileNotFoundError:
        print("File not found:", filepath)

The current output is

1
2
3

4
5
6

7
8
9

The expected output is

4 #(1+4+7)/3
5 #(2+5+8)/3
6 #(3+6+9)/3

答案1

得分: 2

read() 返回一个字符串或字节。您当前正在获取一个字符串。您需要解析每行上的整数,将它们保存在一个列表或numpy数组中,然后可以调用 np.average 来获取您需要的值。

英文:

read() returns either a string or bytes. You're currently getting a string. You need to parse the integers on each line, save them in a list or numpy array and then you can call np.average to get the value you need.

答案2

得分: 1

NFILES = 3

values = [[] for _ in range(NFILES)]

for i in range(NFILES):
with open(f'/Volumes/G-Drive/File{i+1}.txt') as data:
values[i] += map(int, filter(lambda x: x.strip().isdecimal(), data))

for t in zip(*values):
print(sum(t)//len(t))

英文:

You have 3 files. Each file has a number of lines. Each line contains a single integer value

Therefore (using different file paths):

NFILES = 3

values = [[] for _ in range(NFILES)]

for i in range(NFILES):
    with open(f'/Volumes/G-Drive/File{i+1}.txt') as data:
        values[i] += map(int, filter(lambda x: x.strip().isdecimal(), data))

for t in zip(*values):
    print(sum(t)//len(t))

Output:

4
5
6

Note:

If any lines in any of the files contains something that cannot be converted to int then such lines will be ignored

答案3

得分: 0

这是一些用于此目的的示例代码:

contents = "1\n2\n3"
num_array = contents.split("\n")

total = 0
for number in num_array:
    total += int(number)

print(total / len(num_array))

contents 是您从文件中读取的内容。如果文件中不是每一行都是一个数字,那么整数转换会引发异常。

另外,我假设文件中的数字是由换行符分隔的,如果不是的话,您将需要在分割语句中替换字符。

英文:

Here's some sample code for that:

contents = "1\n2\n3"
num_array = contents.split("\n")

total = 0
for number in num_array:
    total += int(number)

print(total / len(num_array))

contents is the content you read from your files. You'll have to watch out if not every line in the file is a number because then the integer conversion will throw an exception.

Also I assume that the numers in the file are separated by newlines, if now you'll have to replace the character in the split statement.

huangapple
  • 本文由 发表于 2023年6月13日 15:42:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定