gpt4 book ai didi

python - 从文本文件的数据中计算平均值

转载 作者:行者123 更新时间:2023-12-04 16:16:49 25 4
gpt4 key购买 nike

我有一个文本文件如下,其中字符串之间有两列:

1   23
2 29
3 21
4 18
5 19
6 18
7 19
8 24
Cluster analysis done for this configuration!

1 23
2 22
3 19
4 18
5 23
6 17
7 19
8 31
9 21
10 27
11 19
Cluster analysis done for this configuration!

1 22
2 26
3 27
4 23
5 25
6 32
7 23
8 19
9 19
10 18
11 30
12 21
13 23
14 16
Cluster analysis done for this configuration!

1 23
2 19
3 23
4 27
5 20
6 17
7 15
8 22
9 16
10 23
11 20
12 23
Cluster analysis done for this configuration!

期望的输出是:

1 22.75
2 24.0
3 22.5
4 21.5
5 21.75
6 21.0
7 19.0
8 24.0
9 18.666666666666668
10 22.666666666666668
11 23.0
12 22.0
13 23.0
14 16.0

我想得到第一列中每个数字的平均值。如果我以这个例子为例,对应于“1”的平均值将是:(23+23+22+23)/4 = 22.75 以此类推,对于“2”、“3”……请注意总数字符串 'Cluster analysis….' 之间的行不一样,但没关系。例如,在这种情况下,“14”的平均值仅为 16,因为除了“3rd” block 之外,没有其他数字对应于“14”。

我一直在想,需要以某种方式打印字符串 'Cluster analysis….' 之间的所有数字,然后可能存储在一个数组中,然后只做一个平均值,但无法在其中实现代码。谁能给我一个线索?

我对编码语言没有任何偏好;它只需要解决问题。我在考虑使用 bash/shell,但也欢迎使用 python。

最佳答案

awk '/^[0-9]+ +[0-9]+$/ { # pick only lines with two numbers
arr[$1] += $2 # accumulate the numbers in indexed bins
n[$1]++ # keep track of how may numbers are in each bin
}
END { # finally,
for (e in arr) # for each bin
print arr[e]/n[e] # divide
}' your_input_file

关于python - 从文本文件的数据中计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62220118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com