简体   繁体   中英

How do I sort a list that I have appended to in Python 3.3

I've been racking my brains trying to figure this out:

for line in test:
    x = line.split()
    y = int(x[1])
    x.append({"Average":str(y)})
    print(x)

What this does is that it attaches the line Average:y to, as an example, James 20 30 0 50 It would then print to the user James 0 0 0 0 {Average: 0} This is my issue: My text document contains multiple different names and numbers like this:

James 20 0 0 0 0
Harrison 7 0 0 0 0
George 9 0 0 0 0

I also made it to calculate averages if there is more than one number above 0. When I append that Average:y, I want to sort the entire list depending on their 'y' so if it was:

James 20 0 0 0 0 {Average: 20}
Harrison 7 0 0 0 0 {Average: 7}
George 9 0 0 0 0 {Average: 9}
Oliver 10 5 6 0 0 {Average: 7}

It would become:

Harrison 7 0 0 0 0 {Average: 7}
Oliver 10 5 6 0 0 {Average: 7}
George 9 0 0 0 0 {Average: 9}
James 20 0 0 0 0 {Average: 20}

I am unable to figure out how to do this as I append each line one by one so if I try to sort it using the sort command it does not work. What I do is append the first line -> print it -> append the second line -> so on.... How could I sort this list based on the appended averages? Thanks for reading and helping!

Tested, hope it works. You can get more items playing with the append function.

test = ["Harrison 20 0 0", "George 40 0 0", "Zohan 30 0 0"]
foo = []
for line in test:
    x = line.split()
    y = int(x[1])
    foo.append({"Name":x[0],"Average":str(y)})
    print(x)
sorted_x = sorted(foo)
print sorted_x

The problem is that you're printing in the loop. Collate the results first, then sort, then print.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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