用Python方式对逗号分隔数字列表进行排序

编程入门 行业动态 更新时间:2024-10-22 05:06:25
本文介绍了用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方式对逗号分隔数字列表进行排序

本文发布于:2023-10-15 02:53:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   方式   数字   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!