[英]How can I find the average of the numbers in a list contained in a string from a text file?
[英]How to find the average from a list of numbers in a text file python
在文本文件中,有一个名称列表以及一个数字,表示在这种情况下的得分。 有没有办法找出文本文件中所有数字的平均值。
码:
print("average calculator")
option = input("option: ")
option_class = input("class: ")
one = "1.txt"
if option.lower() == 'avg' and option_class == '1':
name = input("name: ")
with open(one) as f:
the_list = [int(l.strip().split()[-1]) for l in f if name in l]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print (name,"Average is: ", avg)
代码询问用户名称的部分,在这里查找文本文件中名称旁边的所有数字,但是我试图删除此方面,并允许代码识别文件中的所有数字。 。
文本文件:
Matt 3
Jhon 4
Alex 6
从这些数字[3,4,6]中应该得出平均值,注意:可以附加文本文件,可以添加更多名称和分数。
TIA!
尝试熊猫图书馆。
一些线:
import pandas as pd
df = pd.read_csv('filename.txt', delimiter=' ')
df['Column name'].mean()
它具有轻松过滤和分组数据的功能,并且比编写自己的代码对这种任务有用得多。 我处理的文件超过100,000行,并且可以读取,分组,过滤每个组中的离群值并以大约4行代码计算统计信息。
清单理解:
the_list = [int(l.strip().split()[-1]) for l in f if name in l]
当量:
with open(one) as f:
the_list = [] # creating empty list or (array)
for l in f: # treversing over the lines in file
if name in l: # if input name is in the line do next line
the_list.append(int(l.strip().split()[-1])) # adding element to list
else: # if input name is not in line ignore the line dont use the score
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.