python列表字母排序,在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"]

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

it gives:

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

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.

How do I proceed?

Thank you so much :)

解决方案

You want to use natural sort:

import re

_nsre = re.compile('([0-9]+)')

def natural_sort_key(s):

return [int(text) if text.isdigit() else text.lower()

for text in re.split(_nsre, s)]

Example usage:

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值