Python reduce, lambda, and sorting

Source: Internet
Author: User

Lambda

Lambda is used to compile simple functions.

Lambda is used as follows: lambda arg1, arg2, arg3,..., argn: expression


Fs = [(lambda n, I = I: I + n) for I in range (10)]
>>> Fs [3] (4)
7
>>> Fs [4] (4)
8
>>> Fs [5] (4)
9


Filter

Filter, map, and reduce are all python built-in functions. filter and map are simple, and the values in the list are processed in sequence. The output result is also a list. Reduce uses the values in the column as parameters in sequence and input them to the function. The result may not be a list.


F >>> ilter (lambda x: x % 2 = 0, [1, 2, 4, 5])

[2, 4]


>>> Map (lambda x: x * 2, [1, 2, 3, 4, [5, 6, 7])
[2, 4, 6, 8, [5, 6, 7, 5, 6, 7]


Reduce implementation

 def reduce(bin_func,seq,initial=None):lseq = list(seq)if initial is None:res = lseq.pop(0)else:res = initialfor eachItem in lseq:res = bin_func(res,eachItem)return res

>>> Reduce (lambda x, y: x + y, [1, 2, 4])
10
>>> Reduce (lambda x, y: x + y, [1, 2, 4], 10)
20


In addition, note: filter and map can be replaced by list parsing, and list Parsing is more powerful.

A = [x * 2 for x in range (10)]

A = [x for x in range (10) if x % 3 = 0]

[X + y for x in range (5) if x % 2 = 0 for y in range (10) if y % 2 = 1], list parsing can be a two-tier Loop

List sorting

There are two methods to sort a list. One is to use the list member function, and the other is to use the built-in function sorted.

The list member function has three parameters: list. sort (cmp = None, key = None, reverse = False)

The three parameters are described as follows:

Cmp: cmp specifies a custom comparison function of two arguments (iterable elements) which shold return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal, or larger than the second argument:
"Cmp = lambda x, y: cmp (x. lower (), y. lower ())"
Key: key specifies a function of one argument that is used to extract a comparison key from each list element: "key = str. lower"
Reverse: reverse is a boolean value. if set to True, then the list elements are sorted as if each comparison were reversed. in general, the key and reverse conversion processes are much faster than specifying
Equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

Both cmp and key are functions,

Key is a variable function. The input is an element in the list and the output is a comparable element.

Cmp is a function of two edges. The input value is list and the output value is the size relationship between the two elements (greater than 0, less than 0, or equal to 0)

Key and cmp are usually not used at the same time

The following is an example:

Instance 1:
>>> L = [2, 3, 1, 4]
>>> L. sort ()
>>> L
>>> [1, 2, 4]
Instance 2:
>>> L = [2, 3, 1, 4]
>>> L. sort (reverse = True)
>>> L
>>> [4, 3, 2, 1]
Instance 3:
>>> L = [('B', 2), ('A', 1), ('C', 3), ('D', 4)]
>>> L. sort (cmp = lambda x, y: cmp (x [1], y [1])
>>> L
>>> [('A', 1), ('B', 2), ('C', 3), ('D', 4)]
Instance 4:
>>> L = [('B', 2), ('A', 1), ('C', 3), ('D', 4)]
>>> L. sort (key = lambda x: x [1])
>>> L
>>> [('A', 1), ('B', 2), ('C', 3), ('D', 4)]
Instance 5:
>>> L = [('B', 2), ('A', 1), ('C', 3), ('D', 4)]
>>> Import operator
>>> L. sort (key = operator. itemgetter (1 ))
>>> L
>>> [('A', 1), ('B', 2), ('C', 3), ('D', 4)]
Instance 6: (DSU method: Decorate-Sort-Undercorate)
>>> L = [('B', 2), ('A', 1), ('C', 3), ('D', 4)]
>>> A = [(x [1], I, x) for I, x in enumerate (L)] # I can confirm the stable sort
>>> A. sort ()
>>> L = [s [2] for s in A]
>>> L
>>> [('A', 1), ('B', 2), ('C', 3), ('D', 4)]
In the preceding section, we use the List sorting method in Step 6. instance 3.4.5.6 can be used to sort an item in List item.
Sort the comparison keywords.
Efficiency Comparison:
Cmp <DSU <key
Through experimental comparison, method 3 is slower than Method 6, Method 6 is slower than method 4, and method 4 and Method 5 are basically equivalent.
Sort multiple keywords by comparison:
Instance 7:
>>> L = [('D', 2), ('A', 4), ('B', 3), ('C', 2)]
>>> L. sort (key = lambda x: x [1])
>>> L
>>> [('D', 2), ('C', 2), ('B', 3), ('A', 4)]
We can see that the sorted L is only sorted by the second keyword. If we want to use the second keyword
After sorting, what about sorting with the first keyword? There are two methods
Instance 8:
>>> L = [('D', 2), ('A', 4), ('B', 3), ('C', 2)]
>>> L. sort (key = lambda x :( x [1], x [0])
>>> L
>>> [('C', 2), ('D', 2), ('B', 3), ('A', 4)]
Instance 9:
>>> L = [('D', 2), ('A', 4), ('B', 3), ('C', 2)]
>>> L. sort (key = operator. itemgetter (1, 0 ))
>>> L
>>> [('C', 2), ('D', 2), ('B', 3), ('A', 4)]
Why does instance 8 work? The reason is that tuple is compared from left to right. After comparison, if
Equal, compared to the second

========================================================== ======================================

In python, pass indicates that no processing is performed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.