简体   繁体   中英

How to convert nested list strings to integers then sort them in python 3?

Not an experienced programmer! Currently studying a computing GCSE in school and need help with a problem.

I have a nested list that holds the information of student names and then their score in a text file, this file then needs to be imported into a nested list. I have done this using the code -

scoresave = []
with open('class1quizscoreboard.txt') as scoreboard:
    for line in scoreboard:
        scoresave.append(line.strip().split(','))
print (scoresave)

And this works fine with the output of

[['Emily Scott', ' 7'], ['Student Name', ' 6'], ['Another Student', ' 2']]

This is what I expected, but how would I change the scores of the students into integers?

I have tried multiple solutions from this site that are similar but none have worked for me.

You can use:

sorted(map(lambda x: [x[0], int(x[1])], scoresave), key=lambda x: x[1])

to get what you want.

Explanation:

This converts your nested list's second element into ints.

map(lambda x: [x[0], int(x[1])], scoresave)

We pass that whole into these:

sorted({}, key=lambda x: x[1])

which sorts the list

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