简体   繁体   English

使用文本文件中的信息对列表进行排序

[英]Sort list with information from text file

I have been reading class objects from a text file and stored the information in a list.我一直在从文本文件中读取类对象并将信息存储在列表中。 My question is: How can I sort the list in a numerical order.我的问题是:如何按数字顺序对列表进行排序。

Text file:文本文件:

Hugo 10
Isac 9
John 90
Kelly 8

Code:代码:

class A:
    def __init__(self,name, age):
        self.name = name
        self.age = age

def sort_list():  
    a = list()        
    file = open('my_textfile.txt', 'r').readlines()       
    for k in file:
        k = k.split(' ')
        af = A(k[0], k[1])
        a.append(af)       
    return a

Then I want to sort my list so that both columns get sorted numerically.然后我想对我的列表进行排序,以便两列都按数字排序。 Like this:像这样:

Kelly 8
Isac 9
Hugo 10
John 90

Here is one solution using the code you suggest.这是使用您建议的代码的一种解决方案。 Break the data into two parts sort it and put it back together again.将数据分成两部分进行排序,然后再将其重新组合在一起。 There are other ways of doing this with pandas.还有其他方法可以用熊猫来做到这一点。

class A:
    def __init__(self,name, age):
        self.name = name
        self.age = age
def sort_list():  
    a = list()        
    name = list()
    data = list()
    file = open('my_textfile.txt', 'r').readlines()       
    for k in file:
        k = k.split(' ')
        name.append(k[0])
        data.append(k[1])
    name.sort()
    data.sort()
    length = len(name)
    for i in range(length):
        af = A(name[i], data[i])
        a.append(af)
    return a

You most likely have found a solution now.您现在很可能已经找到了解决方案。 If not, let me suggest something.如果没有,让我提出一些建议。

First, I made a slight modification to your class: I added a string representation that makes prints more readable:首先,我对您的类进行了轻微修改:我添加了一个字符串表示,使打印内容更具可读性:

class A:

    def __repr__(self):
        return f"A('{self.name}', {self.age})"

    def __init__(self, name, age):
        self.name = name
        self.age = age

You don't need that for the following!您不需要为以下内容!

Now the sorting:现在排序:

def sort_list():
    lst = list()
    lines = open('my_textfile.txt', 'r').readlines()
    for line in lines:
        line = line.split()
        lst.append(A(line[0], int(line[1])))
    lst.sort(key=lambda a: (a.age, a.name))
    return lst

Apart from renaming some variables I have made the following adjustments:除了重命名一些变量外,我还进行了以下调整:

  • I converted the second part of the strings to an int because I think that's what you actually want ( int(line[1]) ).我将字符串的第二部分转换为int因为我认为这就是您真正想要的( int(line[1]) )。
  • After appending all the data to the list it get's sorted.将所有数据附加到列表后,它会被排序。 Lists have a sort method, but in your case you have to give it some hints on how to sort, since the elements are a new class.列表有一个sort方法,但在你的情况下,你必须给它一些关于如何排序的提示,因为元素是一个新类。 The hint is the lambda function given to the optional key argument of sort .提示是给sort的可选key参数的 lambda 函数。 It returns for every element of the list the tuple (a.age, a.name) .它为列表的每个元素返回元组(a.age, a.name) sort then actually sorts according to this values. sort然后实际上根据这个值进行排序。 Since the age is first, the sorting looks a it first and the result is an increasing age in the final list.由于年龄是第一个,排序首先看起来是它,结果是最终列表中的年龄增加。 For entries with same age the sorting proceeds in alphabetical order on the names.对于年龄相同的条目,按名称的字母顺序进行排序。

The result of的结果

lst = sort_list()
print(lst)

is

[A('Kelly', 8), A('Isac', 9), A('Hugo', 10), A('John', 90)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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