![](/img/trans.png)
[英]How do I sort my text file if it has Integers and Strings in Python
[英]Select and sort integers/strings from a text file in Python
我有以下当前这样设置的文本文件(Results.txt):
Sophie
3
6
9
Laura
8
5
15
Alan
10
4
6
我试图以不同的方式选择和排序此数据。 到目前为止,我的代码如下所示:
file = open('Results.txt', 'r')
lines = file.read().splitlines()
a = int(lines[1])
b = int(lines[2])
c = int(lines[3])
d = int(lines[5])
e = int(lines[6])
f = int(lines[7])
g = int(lines[9])
h = int(lines[10])
i = int(lines[11])
name1=lines[0]
name2=lines[4]
name3=lines[8]
allnames=[name1, name2, name3]
allnames.sort()
student1 = [a,b,c]
student2 = [d,e,f]
student3 = [g,h,i]
s1high=max(student1)
s2high=max(student2)
s3high=max(student3)
file.close()
我希望我的程序能够:
...并将其输出到屏幕
如您所见,我已经开始从文本文件导入结果并将其转换为整数,但是肯定有一些更快的方法可以做到这一点吗?
我不确定您所说的意思是“ ...并显示学生的最高分数按平均分数排序,从高到低按最高分数排序,从高到低...”
也许这段小代码可以让您开始自己想做的事情。
file = open('Results.txt', 'r')
lines = file.read().splitlines()
my_dict = {}
key = None
# creating a dict with your data
for line in lines:
if line.isalpha():
key = line
my_dict[key] = []
else:
my_dict[key].append(int(line))
# printing your data
# iterating on sorted by key dict
for student in sorted(my_dict):
print(student)
# iterating the sorted list
for score in sorted(my_dict[student], reverse=True):
print(score)
看看这是不是你想要的
为了从文件中读取内容,您可以使用
s = {lines[i]:[float(k) for k in lines[i+1:i+4]] for i in range(0,len(lines),4)}
这给了学生字典vs标记这样的东西
s = {'Laura': [8, 5, 15], 'Sophie': [3, 6, 9], 'Alan': [10, 4, 6]}
要根据字母排序,可以使用
for i in sorted(s.keys()):
print i,max(s[i])
同样根据平均值进行排序
# function which returns avg mark given the name
avg_mark = lambda name:sum(s[name])/len(s[name])
for i in sorted(s.keys(),key=avg_mark,reverse=True):
print i,avg_mark(i)
同样根据最高分进行排序
# function which returns highest mark given the name
high_mark = lambda name:max(s[name])
for i in sorted(s.keys(),key=high_mark,reverse=True):
print i,high_mark(i)
希望这会帮助你。 如果您需要任何解释,请随时发表评论
也许是这样的吗? 在CPython 2. [67],CPython 3. [01234],Pypy 2.4.0,Pypy3 2.3.1和Jython 2.7b3上运行:
#!/usr/local/cpython-3.4/bin/python
# pylint: disable=superfluous-parens
# superfluous-parens: Parentheses are good for clarity and portability
'''Get student grades'''
# port pprint
import decimal
import collections
def main():
'''Main function'''
students = collections.defaultdict(list)
with open('input', 'r') as file_:
for line in file_:
line_sans_newline = line.rstrip('\n')
if line_sans_newline.isalpha():
name = line_sans_newline
else:
students[name].append(decimal.Decimal(line))
names = list(students)
names.sort()
for name in names:
max_grade = max(students[name])
print('{0} {1}'.format(name, max_grade))
main()
高温超导
val=[]
keys=[]
i=0
l=[]
lines=open('Result.txt','r').readlines()
for line in lines:
try:
val.append(int(line))
except:
keys.append(line)
for i in range(0,len(val),3):
h=val[i:i+3]
h.sort()
l.append(h[::-1])
print 'Sort the test results alphabetically and show the students highest score.\n'
for i,j in zip(keys,l):
print i,j
print 'Sort by the average score, highest to lowest.'
avlist=[float(sum(i))/len(i) for i in l ]
print avlist
while(len(avlist)):
for i,j in zip(keys,avlist):
if j==max(avlist):
print i,j
avlist.remove(j)
print '\nSort by the highest score, highest to lowest.\n'
hlist=[max(i) for i in l ]
hlist.sort()
hlist=hlist[::-1]
for k in hlist:
for i,j in zip(keys,l):
if max(j)==k:
print i,j
结果:
Sort the test results alphabetically and show the students highest score.
Sophie
[9, 6, 3]
Laura
[15, 8, 5]
Alan
[10, 6, 4]
Sort by the average score, highest to lowest.
[6.0, 9.333333333333334, 6.666666666666667]
Laura
9.33333333333
Alan
6.66666666667
Sophie
6.0
Sort by the highest score, highest to lowest.
Laura
[15,8,5]
Alan
[10,6,4]
Sophie
[9,6,3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.