簡體   English   中英

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM