python二维表中字符串转数字_Python-在包含字符串和数字的列表中对数字值进行排序...

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

The scores .txt file:

Dan Danson,9,6,1

John Johnson,5,7,10

Mike Mikeson,10,7,6

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)

Now I have this list:

[['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

解决方案

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:], ..): 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值