简体   繁体   English

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

[英]How to sort list of String without considering Special characters and with case insensitive

Please let me know how to sort the list of String in either ascending / descending order without considering special characters and case. 请告诉我如何按升序/降序对字符串列表进行排序,而不考虑特殊字符和大小写。

ex: 例如:

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

Applying the list.sort /sorted method results in sorted list 应用list.sort / sorted方法会生成排序列表

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

but the without considering the special characters and case it should be 但不考虑特殊字符和案例应该是

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

list.sort /sorted method sorts based on the ascii value of the characters but Please let me knwo how do i achieve my expected one list.sort / sorted方法根据字符的ascii值排序但是请告诉我如何实现我期望的一个

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

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

It depends on what you mean by "special" characters - but whatever your definition, the easiest way to do this is to define a key function. 这取决于你对“特殊”字符的意思 - 但无论你的定义如何,最简单的方法是定义一个key功能。

If you only care about letters: 如果你只关心字母:

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

If you care about digits as well: 如果你也关心数字:

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

If you care about letters and digits and you want digits to sort after letters (which looks like it might be the case from your example output): 如果您关心字母和数字, 并且您希望数字在字母后排序(看起来可能是您的示例输出中的情况):

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

This last one takes advantage of the fact that "z" comes 74 places after "0" in ASCII. 最后一个利用了“z”在ASCII中“0”后出现74位的事实。

您也可以这样排序:

new_item_list.sort(key= lambda x: ''.join(e for e in x.get_author_name() if e.isalnum()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM