我有一个关于从文本文件中获取数据的问题,该文本文件包括简单地添加/平均来自文件内不同行的数据。从包含字符串和整数的文本文件中获取数据(Python)
pos1 250 184 196
pos2 167 321 459
我需要添加整数250
和167
并产生一个总。我很乐于在同一行上添加整数,并获得总数,平均值等(总计250 + 184 + 196)。
def calculateTotal():
for i in range(1):
userChoice2 = int(input(
"1. Total feedback that is good.\n2. Total feedback that is fair.\n3."
" Total feedback that is poor.\n......:")) -1
if userChoice2 > 3:
time.sleep(0.5)
print(
"\n******************************\nInvalid choice, please choose again.\n******************************\n")
time.sleep(0.5)
calculateTotal()
else:
goodfeedback2 =
fairFeedback2 =
poorFeedback2 =
print("Total good feedback is: ", goodfeedback2)
time.sleep(1)
allDepartments = readData("data.txt")
我刚刚就如何解决它的一些建议。
total = allDepartments[userChoice][1] + allDepartments[userChoice][2] + allDepartments[userChoice][3]
avg = (allDepartments[userChoice][1] * 3 + allDepartments[userChoice][2] * 2 + allDepartments[userChoice][
3])/total
time.sleep(1)
print('\nThe average is: ', format(avg, '.2f'), ' and the total number of votes for that department is:',
total, '\n******************************\n\n.....LOADING MENU.....\n')
如果你想从文本文件中得到一个numpy数组,你可以简单地使用'numpy.loadtxt'。不需要额外的模块。 – Mel
@tmoreau好点!如果文本文件非常简单并且没有缺失单元格,[genfromtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html#numpy.genfromtxt)以获得更大的灵活性。谢谢! – joris255