gpt4 book ai didi

python - 解析时出现意外的 EOF;尝试计算每行读数的平均值/最大/最小值

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:36 25 4
gpt4 key购买 nike

数据如下所示:

line = infile.readlines()
line

['56047257 16 17 19 16 12 15 12 20 58 123 59\n',
'97231934 18 16 13 19 16 12 13 18 72 101 55\n',
....same]

我想通过使用下面的循环获得 2 到 9 列的平均值并获得 2 到 12 列的最大值和最小值,但它一直给我一个错误:

 File "<string>", line unknown

^
SyntaxError: unexpected EOF while parsing

这就是我的代码:

def main():
#read data in
infile = open('data.txt', 'r')
sun = 0.0
count = 0
line = infile.readline()
while line != "":

ID = line.split(" ")
min_val = float('inf')
max_val = -float('inf')
count_min = 0
count_max = 0
for xStr in line.split(' ')[1:9]:
sun = sun + eval(xStr)
count = count + 1
avg = round(sun / count, 2)
val = eval(xStr)
if val < min_val:
min_val = val
count_min = 1
elif val == min_val:
count_min += 1

if val > max_val:
max_val = val
count_max = 1
elif val == max_val:
count_max += 1
line = infile.readline()

print (ID, ' ',avg,' ',min_val,' ',max_val)

main()

最佳答案

请注意帖子评论部分中提出的问题,但话虽如此,这是获得所需输出的更简单的方法:

def main():
#read data in
infile = open('data.txt', 'r')
average = max_val = min_val = 0.0
count1=count2 = 0
line = infile.readlines()
for x in [x.strip().split() for x in line[:9]]:
x = ID =map(int, x)
average = (average + (sum(x)/len(x)))/len(x)
print average
for x in [x.strip().split() for x in line[:12]]:
x = map(int, x)
val=max(x)
if count1 !=0 and val>max_val:
max_val = val
val=min(x)
if count2 !=0 and val<min_val:
min_val = val
if count1==0:
max_val=max(x)
min_val=min(x)
count1=count2=1

print (ID, ' ',average,' ',min_val,' ',max_val)

main()

注意:您应该尽量不要将infinty分配给变量。通常总是有更好的选择

关于python - 解析时出现意外的 EOF;尝试计算每行读数的平均值/最大/最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29157771/

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