在python中排序-如何对包含字母数字值的列表进行排序? [英] Sorting in python - how to sort a list containing alphanumeric values?

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

问题描述

我有一个包含以下详细信息的列表:

I have a list that consists of details like this:

list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]

现在,我要对该列表进行排序,以使值按以下顺序排列:

now, i want to sort this list, such that the values are in the following order:

list1 = ["1", "2C", "36", "100A", "132", "302F", "342B"]

仅执行list1.sort()显然不能给出正确的答案- 它给出了:

Just doing list1.sort() obviously doesn't give the correct answer - it gives:

list1 = ["1", "100A", "132", "2C", "36", "302F", "342B"]

我假设这是因为python直接将所有这些都视为字符串. 但是,我想根据它们的数值FIRST对其进行排序,然后再根据数字后面的字符对其进行排序.

I'm assuming this is because python treats all these as strings directly. However, I want to sort them based on their numeric value FIRST, and then the character that follows the number.

我该如何进行?

非常感谢您:)

推荐答案

您要使用示例用法:

>>> list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]
>>> list1.sort(key=natural_sort_key)
>>> list1
['1', '2C', '36', '100A', '132', '302F', '342B']

此功能是通过将元素拆分为多个列表来分离出数字并将它们比较为整数而不是字符串:

This functions by splitting the elements into lists separating out the numbers and comparing them as integers instead of strings:

>>> natural_sort_key("100A")
['', 100, 'a']
>>> natural_sort_key("342B")
['', 342, 'b']

请注意,仅当您始终将int与int和字符串与字符串进行比较时,这才在Python3中起作用,否则会出现TypeError: unorderable types异常.

Note that this only works in Python3 if you are always comparing ints with ints and strings with strings, otherwise you get a TypeError: unorderable types exception.

这篇关于在python中排序-如何对包含字母数字值的列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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