def byalphabet():
if classchoice == '1':
with open("newFile.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
alphabetical = []
for i in range (0, len(scores)):
line = scores[i].rstrip('\n')
alphabetical.append(line)
alphabetical = sorted(alphabetical)
for i in range (0, len(alphabetical)):
print (alphabetical[i])
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
if name not in user_scores or user_scores[name] < score:
user_scores[name] = score
for name in sorted(user_scores):
print(name, '-', user_scores[name])
elif classchoice == '2':
with open("newFile2.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
alphabetical = []
for i in range (0, len(scores)):
line = scores[i].rstrip('\n')
alphabetical.append(line)
alphabetical = sorted(alphabetical)
for i in range (0, len(alphabetical)):
print (alphabetical[i])
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
if name not in user_scores or user_scores[name] < score:
user_scores[name] = score
for name in sorted(user_scores):
print(name, '-', user_scores[name])
else:
with open("newFile3.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
alphabetical = []
for i in range (0, len(scores)):
line = scores[i].rstrip('\n')
alphabetical.append(line)
alphabetical = sorted(alphabetical)
for i in range (0, len(alphabetical)):
print (alphabetical[i])
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
if name not in user_scores or user_scores[name] < score:
user_scores[name] = score
for name in sorted(user_scores):
print(name, '-', user_scores[name]) ` 我的程序似乎输出了比所需的更多的值
Aaron - 4
Joeseph - 10
Joeseph - 3
Joeseph - 4
Joeseph - 5
Test1 - 1
Test1 - 10
Test1 - 6
Test2 - 4
Zzron - 1
Aaron - 4
Joeseph - 10
Test1 - 10
Test2 - 4
Zzron - 1发布于 2015-07-12 03:14:56
更详细的版本:
import io
file0 = io.StringIO('''Aaron - 4
Joeseph - 10
Joeseph - 3
Joeseph - 4
Joeseph - 5
Test1 - 1
Test1 - 10
Test1 - 6
Test2 - 4
Zzron - 1
Aaron - 4
Joeseph - 10
Test1 - 10
Test2 - 4
Zzron - 1''')
def read_file(fle):
data = {}
for line in fle.readlines():
splt = line.split(' - ')
if len(splt) == 2:
name, score = splt[0], int(splt[1])
if not name in data:
data[name] = score
continue
else:
if score > data[name]:
data[name] = score
continue
return data
def print_data(data):
for name, score in sorted(data.items()):
print('{} - {}'.format(name, score))
data = read_file(file0)
print_data(data)输出:
Aaron - 4
Joeseph - 10
Test1 - 10
Test2 - 4
Zzron - 1https://stackoverflow.com/questions/31359929
复制相似问题