classs = input("Class [1, 2 or 3] - ")
if clas
data = f.readlines()
for le:
print(line)
found = True
if found == False:
print("False")
这是典型的打印输出:
John = 10
John = 6
John = 4
我需要能够仅使用10, 4, 6
来创建平均值,因为我需要知道一种方法来隔离其余的并允许数字继续以创建平均分数。
希望有人能理解这一点,并能够提供帮助!
先谢谢!
答案 0 :(得分:0)
如果每个行的格式相同,您可以使用string.split
并转换为int
:
classs = input("Class [1, 2 or 3] - ")
l = []
if classs =='1':
name = input("What is your name? - ")
datafile = '1.txt'
found = False
with open(datafile, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print(line)
l.append(int(line.split()[2]))
found = True
if found == False:
print("False")
然后查看数字列表并获得平均数,例如:
total = 0
num = 0
for x in l:
total = total + x
num = num + 1
print(total/num)
答案 1 :(得分:0)
一种方法是从列表中提取每个玩家的最后3个数字(我假设您只需要3个,如果不是这个代码可以更改更多)
RunStats
这将为您提供2D数组。内部的每个较小的数组都会在第0和第1,2和第3个数据处指定人名。现在你有了这些,你可以简单地算出平均值。
Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
count = 0
record = line
studentList = record.split(': ')
score = studentList[1].strip('\n')
studentList = [studentList[0], score]
if len(dataList) == 0:
dataList.append(studentList)
else:
while count < len(dataList):
if studentList[0] == dataList[count][0]:
if len(dataList[count]) == 4:
dataList[count][3] = dataList[count][2]
dataList[count][2] = dataList[count][1]
dataList[count][1] = score
break
dataList[count].append(score)
break
elif count == len(dataList) - 1:
dataList.append(studentList)
break
count = count + 1
长篇大论且效率低下,但我能用我对python的小知识做到最好:)
答案 2 :(得分:0)
如果这是1.txt
的内容:
John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13
将&#34;替换为&#34;声明:
name = "John"
_class = 1
with open("%s.txt" % _class, "r") as out:
lines = out.readlines()
scores = []
for line in lines:
if name in line:
# "strip" without arguments strips out all beginning
# and trailing white-space (i.e. " ", "\n", "\r").
line = line.strip()
score = int(line.split(" = ")[1])
scores.append(score)
# If there isn't any scores in this list, then there was no user
# data.
if scores:
# Use python built-in sum to sum the list of scores and
# divide the result by the number of scores gives you the average.
average = sum(scores) / len(scores)
print "%s's average score is %.1f out of %d game(s)." % (
name, average, len(scores))
else:
print "User %s not found." % name