如何排序字符串列表而不考虑特殊字符和不区分大小写

问题描述 投票:2回答:3

请告诉我如何按升序/降序对字符串列表进行排序,而不考虑特殊字符和大小写。

例如:

list1=['test1_two','testOne','testTwo','test_one']

应用list.sort / sorted方法会生成排序列表

['test1_two', 'testOne', 'testTwo', 'test_one']

但不考虑特殊字符和案例应该是

['testOne','test_one', 'test1_two','testTwo'] OR 
['test_one','testOne','testTwo', 'test1_two' ]

list.sort / sorted方法根据字符的ascii值排序但是请告诉我如何实现我期望的一个

python python-2.7 sorting
3个回答
7
投票

如果用特殊字符表示“一切不是字母”:

sorted(list1, key=lambda x: re.sub('[^A-Za-z]+', '', x).lower())

3
投票

这取决于你对“特殊”字符的意思 - 但无论你的定义如何,最简单的方法是定义一个key函数。

如果你只关心字母:

from string import letters, digits

def alpha_key(text):
    """Return a key based on letters in `text`."""
    return [c.lower() for c in text if c in letters]

>>> sorted(list1, key=alpha_key)
['testOne', 'test_one', 'test1_two', 'testTwo']

如果你也关心数字:

def alphanumeric_key(text):
    """Return a key based on letters and digits in `text`."""
    return [c.lower() for c in text if c in letters + digits]

>>> sorted(list1, key=alphanumeric_key)
['test1_two', 'testOne', 'test_one', 'testTwo']

如果您关心字母和数字,并且您希望数字在字母后排序(看起来可能是您的示例输出中的情况):

def alphanum_swap_key(text):
    """Return a key based on letters and digits, with digits after letters."""
    return [ord(c.lower()) % 75 for c in text if c in letters + digits]

>>> sorted(list1, key=alphanum_swap_key)
['testOne', 'test_one', 'testTwo', 'test1_two']

最后一个利用了“z”在ASCII中“0”后出现74位的事实。


0
投票

您也可以这样排序:

new_item_list.sort(key= lambda x: ''.join(e for e in x.get_author_name() if e.isalnum()))
© www.soinside.com 2019 - 2024. All rights reserved.