Sort list of strings by a part of the string

后端 未结 4 1543
余生分开走
余生分开走 2020-12-03 05:40

I have a list of strings which have the following format:

[\'variable1 (name1)\', \'variable2 (name2)\', \'variable3 (name3)\', ...]

... an

相关标签:
4条回答
  • 2020-12-03 05:45

    To change sorting key, use the key parameter:

    >>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
    >>> s.sort(key = lambda x: x.split()[1])
    >>> s
    ['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
    >>> 
    

    Works the same way with sorted:

    >>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
    >>> sorted(s)
    ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
    >>> sorted(s, key = lambda x: x.split()[1])
    ['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
    >>> 
    

    Note that, as described in the question, this will be an alphabetical sort, thus for 2-digit components it will not interpret them as numbers, e.g. "11" will come before "2".

    0 讨论(0)
  • 2020-12-03 06:00

    You can use regex for this:

    >>> import re
    >>> r = re.compile(r'\((name\d+)\)')
    >>> lis = ['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']
    >>> sorted(lis, key=lambda x:r.search(x).group(1))
    ['variable1 (name1)', 'variable2 (name100)', 'variable3 (name3)']
    

    Note that above code will return something like name100 before name3, if that's not what you want then you need to do something like this:

    >>> r = re.compile(r'\(name(\d+)\)')
    def key_func(m):
        return int(r.search(m).group(1))
    
    >>> sorted(lis, key=key_func)
    ['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']
    
    0 讨论(0)
  • 2020-12-03 06:01

    Just use key parameter of sort method.

    test.sort(key = lambda x: x.split("(")[1])
    

    Good luck!

    Edit: test is the array.

    0 讨论(0)
  • 2020-12-03 06:05

    The solution is:

    sorted(b, key = lambda x: x.split()[1])
    

    Why? We want to sort the list (called b). As a key we will use (name X). Here we assume that it will be always preceded by space, therefore we split the item in the list to two and sort according to the second.

    0 讨论(0)
提交回复
热议问题