python - lambda expressions used in the sort function

1.lambda expression in general usage

grammar:

lamda argument:expression

example:

add = lambda x, y: x+y
print(add(10, 20))
>>> 30

2.lambda expressions used in the sort function

If A is a time, the list is sorted by the list of tuples, we need to use the parameter key, i.e. keywords, as shown in the code below, lambda is an anonymous function, writing is fixed; x is anonymous function input, that element in the list, in this case, represents a tuple, x is just a temporary name from, you can use any name; x [0] represents the output of the anonymous function, that is, in the first tuple element, i.e., key = x [0]; it is meant the command sentence is sorted by a first element in the list.

a = [('b', 4), ('a', 12), ('d', 7), ('h', 6), ('j', 3)]
a.sort(key=lambda x: x[0])
print(a)
>>>[('a', 12), ('b', 4), ('d', 7), ('h', 6), ('j', 3)]

3. For example, a question of leetcode

937. rearrange log

 

Do you have a log array of logs. Each log is a space-delimited string.

 

For each log, which is the first word alphanumeric identifier. Then, either:

 

Behind each word identifier only lowercase letters, or;
each word identifier will be later made up of numbers only.
We log these two are called letters and numbers logs logs. Each log is to ensure that at least one word following the identifier.

 

Log reordered so that all the letters are sorted before digital log log. Log letters sorted in alphabetical order contents, the identifier is ignored; at the same content, sorted by identifier. It should be arranged in the digital log according to the original order.

 

Returns the final order of the log.

Example:

输入:["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
输出:["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]

Ideas: first log log array is divided into two arrays logs, a log store letters, a log memory number, meaning of the questions, the need to log all letters ahead of the digital log, log alphabetic letters sorted by content, it is only for letters log sorting an array, and returns two arrays homesick results on OK.

code show as below:

class Solution(object):
    def reorderLogFiles(self, logs):
        """
        :type logs: List[str]
        :rtype: List[str]
        """
        l1=[]
        l2=[]
        for l in logs:
            if l[-1].isalpha():
                l1.append(l)
            else:
                l2.append(l)
        l1.sort(key=lambda x:(x[x.index(' ')+1:],x[:x.index(' ')]))
        return l1+l2

  

 

Guess you like

Origin www.cnblogs.com/lovewhale1997/p/11424429.html
Recommended