简体   繁体   English

在Python中从文本文件中选择整数/字符串并对其进行排序

[英]Select and sort integers/strings from a text file in Python

I have the following text file (Results.txt) that is currently set up like this: 我有以下当前这样设置的文本文件(Results.txt):

Sophie
3
6
9
Laura
8
5
15
Alan
10
4
6

I am trying to select and sort this data in different ways. 我试图以不同的方式选择和排序此数据。 So far my code looks like this: 到目前为止,我的代码如下所示:

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()

I would like my program to be able to: 我希望我的程序能够:

  • Sort the test results alphabetically and show the students highest score. 按字母顺序对测试结果进行排序,并向学生显示最高分数。
  • Sort by the average score, highest to lowest. 按平均分数排序,从高到低。
  • Sort by the highest score, highest to lowest. 按最高分数排序,从高到低。

...and output this to the screen ...并将其输出到屏幕

As you can see I've started to import the results from the text file and convert them to integers, but surely there must be some quicker way to do this? 如您所见,我已经开始从文本文件导入结果并将其转换为整数,但是肯定有一些更快的方法可以做到这一点吗?

I am not sure what you meant by saying "...and show the students highest score Sort by the average score, highest to lowest Sort by the highest score, highest to lowest..." 我不确定您所说的意思是“ ...并显示学生的最高分数按平均分数排序,从高到低按最高分数排序,从高到低...”

Maybe this little code will get you started on what you wish to do. 也许这段小代码可以让您开始自己想做的事情。

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)

See if this is what you want 看看这是不是你想要的

For reading the content from the file you can use 为了从文件中读取内容,您可以使用

s = {lines[i]:[float(k) for k in lines[i+1:i+4]] for i in range(0,len(lines),4)}

This gives a dictionary of students vs marks something like this 这给了学生字典vs标记这样的东西

s = {'Laura': [8, 5, 15], 'Sophie': [3, 6, 9], 'Alan': [10, 4, 6]}

For sorting according to alphabets you can use 要根据字母排序,可以使用

for i in sorted(s.keys()):
    print i,max(s[i])

similarly for sorting according to average 同样根据平均值进行排序

# 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)

similarly for sorting according to highest marks 同样根据最高分进行排序

# 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)

Hope this will help you. 希望这会帮助你。 Feel free to comment if you need explanation for anything 如果您需要任何解释,请随时发表评论

Maybe something like this? 也许是这样的吗? Runs on CPython 2.[67], CPython 3.[01234], Pypy 2.4.0, Pypy3 2.3.1 and Jython 2.7b3: 在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()

HTH 高温超导

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

Result: 结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM