用Python方式对逗号分隔数字列表进行排序 [英] Pythonic Way to Sort a List of Comma Separated Numbers

查看:821
本文介绍了用Python方式对逗号分隔数字列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本输入

20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051

我从文件中读取它作为

lin = [i.strip() for i in open(sys.argv[1]).readlines()]

该列表看起来像['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']

我的希望是找到对列表进行排序的最pythonic方法,首先对第一个值进行排序,然后对第二个值进行排序,使其看起来像这样:

My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:

['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]

我目前正在尝试将其转换为键值对列表,但我不确定这是正确的选择.

I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.

推荐答案

最简单的方法是将对解析为列表,然后对它们进行排序:

The easiest thing to do is to parse the pairs into lists and then just sort them:

lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)

如果要按数字排序,只需将其转换为数字即可:

In case you want to sort numerically, just cast to numbers:

lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)

这篇关于用Python方式对逗号分隔数字列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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