将in循环转换为while循环



我在一门基础编程课程中有这样的任务,我需要使用while循环而不是for循环来转换代码,但我不知道如何进行

这是我到目前为止的代码

def read_txt(file_txt):
file = open(file_txt, "r")
lines = file.readlines()
file.close()
return lines

file_txt = input("file: ")
lines = read_txt(file_txt)
for l in lines:
asd = l.split(",")
length = len(asd)
score = 0
for i in range(1, length):
score += int(asd[i])
average = score / (length-1)
print(asd[0], average)
file text is like this
edward,4,3,1,2
sara,5,4,1,0
def read_txt(file_txt):
file = open(file_txt, "r")
lines = file.readlines()
file.close()
return lines

file_txt = input("file: ")
lines = read_txt(file_txt)
lines.reverse()
while lines:
l = lines.pop()
asd = l.split(",")
length = len(asd)
score = 0
i = 1
while i < length:
score += int(asd[i])
i += 1
average = score / (length-1)
print(asd[0], average)

现在,在这个while循环中,它将遍历行,直到行为空。它会一个接一个地弹出项目。

For循环比while循环更适合在文件中的行上迭代。这里很少有改进,(1(使用内置的sum,而不是手动相加分数;(2(如果文件太大,不要一次读取文件中的所有行。

file_txt = input("file: ")
with open(file_txt) as f:
while True:
line = f.readline()
if not line:
break
name, scores = line.split(',', maxsplit=1)
scores = scores.split(',')
avg = sum(int(s) for s in scores) / len(scores)
print(f'{name} {avg}')

正如您在上面看到的,检查if not line以确定我们是否在while循环中到达了文件的末尾,这在for循环中是不需要的,因为它实现了__iter__协议。

Python 3.8海象操作符通过::使这一点稍微容易一些

file_txt = input("file: ")
with open(file_txt) as f:
while line := f.readline():
name, scores = line.split(',', maxsplit=1)
scores = scores.split(',')
avg = sum(int(s) for s in scores) / len(scores)
print(f'{name} {avg}')

下面给出了完全相同的输出,而不使用任何for循环。

filename = input("file: ")
with open(filename) as f:
f = f.readlines()
n = []
while f:
v = f.pop()
if v[-1] == 'n':
n.append(v.strip('n'))
else:
n.append(v)
d = {}
while n:
v = n.pop()
v = v.split(',')
d[v[0]] = v[1:]
d_k = list(d.keys())
d_k.sort(reverse=True)
while d_k:
v = d_k.pop()
p = d[v]
n = []
while p:
a = p.pop()
a = int(a)
n.append(a)
print(str(v), str(sum(n)/len(n)))

输出:

edward 2.5
sara 2.5

最新更新