Python-在包含字符串和数字的列表中对数字值进行排序 [英] Python - Ordering Number Values in a List Containing Strings and Numbers

查看:1217
本文介绍了Python-在包含字符串和数字的列表中对数字值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个列表,其中包含python分数文件中的所有信息.

I have Created a list which contains all of the information from a scores file in python.

得分.txt文件:

Dan Danson,9,6,1
John Johnson,5,7,10
Mike Mikeson,10,7,6

我这样做是为了将.txt文件中的信息获取到二维列表中:

I did this to get the information from the .txt file into a 2d list:

f = open(filename, 'r')
lines = f.readlines()
f.close()

scores = []
for line in lines: #Loads lines into a 2d list
    currentline = line.strip('\n').split(",")
    scores.append(currentline)

现在我有了这个列表:

[['Dan Danson', '1', '6', '9'], ['John Johnson', '5', '7', '10'], ['Mike Mikeson', '10', '7', '6']]

从此列表中,我想对列表中的数字进行排序,以使它们从最高到最低排序,因此我得到一个看起来像这样的列表:

From this list I would like to sort the numbers in the list so that they are ordered from highest to lowest so i get a list that looks like this:

[['Dan Danson', '9', '6', '1'], ['John Johnson', '10', '7', '5'], ['Mike Mikeson', '10', '7', '6']]

最后,我希望能够按从高到低的顺序打印列表.

Finally I want to be able to print the list ordered highest to lowest.

Mike Mikeson,10,7,6
John Johnson,10,7,5
Dan Danson,9,6,1

推荐答案

使用 sorted ,其中 int 作为关键功能:

Using sorted with int as a key function:

>>> rows = [
...     ['Dan Danson', '1', '6', '9'],
...     ['John Johnson', '5', '7', '10'],
...     ['Mike Mikeson', '10', '7', '6'],
... ]
>>>
>>> rows = [row[:1] + sorted(row[1:], key=int, reverse=True) for row in rows]
>>> sorted(rows, key=lambda row: sum(map(int, row[1:])), reverse=True)
[['Mike Mikeson', '10', '7', '6'],
 ['John Johnson', '10', '7', '5'],
 ['Dan Danson', '9', '6', '1']]

  • sorted(row[1:], ..):单独的数字值和排序.
  • row[:1]:名称作为列表,或者您可以使用[row[0]].应该是要连接到数字字符串列表的列表.
    • sorted(row[1:], ..): separate number values and sort.
    • row[:1]: name as a list, alternatively you can use [row[0]]. Should be a list to be concatenated to a list of number strings.
    • 这篇关于Python-在包含字符串和数字的列表中对数字值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆