用find :
def split_name(s):
# 传入string, 返回list
ans = []
index1 = 0
while True:
index2 = s.find(" ", index1)
if index2 == -1:
ans.append(s[0:index1-1])
ans.append(int(s[index1:-1]))
break
index1 = index2+1
return ans
f = open('score.txt','r')
students = tuple(f.readlines())
f.close()
name_list = []
i = 0
for student in students:
name_list.append(split_name(student))
sorted_ans = sorted(name_list, key=(lambda x:x[1]), reverse=True)
# x为name_list中的可迭代对象(一维列表),这里只取一维列表的下标为1的元素进行比较
print(sorted_ans)
用 split + strip + join:
f = open('score.txt','r')
students = tuple(f.readlines())
f.close()
name_list = []
i = 0
for student in students:
student.strip('\n')
raw = student.split()
score = raw.pop()
name = ' '.join(raw)
name_list.append([name, int(score)])
sorted_ans = sorted(name_list, key=(lambda x:x[1]), reverse=True)
# x为name_list中的可迭代对象(一维列表),这里只取一维列表的下标为1的元素进行比较
print(sorted_ans)
刚发现没有将字符串类型的分数转为整形...还有排序没逆序...改了一下