Built-in function 2, built-in Function
Built-in function information in part 2
In python3, filter, map, and reduce are no longer built-in functions, that is, <build-in function>. in python3, the three are classes, and the returned results are iterated objects.
1. filter (function, iterable)
Use function filter conditions to obtainIterableThe data you want.
From collections import Iteratortest_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] f = filter (lambda x: x % 3 = 0, test_list) # filter returns an Iterator print (isinstance (f, Iterator) f. _ next _ () for I in f: print (I) # output True69
2. map (
Function,
Iterable)
Take a function and an iteratable object (such as a list), and act the function on each element of the sequence in sequence to form a new iterator.
From collections import Iteratordef f (x): return 2 * x # define a function t_list = [1, 2, 3, 4, 5] function = map (f, t_list) print (isinstance (function, Iterator) # print (function. _ next _ () function. _ next _ () for I in function: print (I) # output True46810
3. reduce (function, iterable)
Reduce acts as a function in an iterative sequence. This function must receive two parameters. reduce calculates the result continuation and the next element of the sequence.
The reduce function does not belong to build-in python3, but is in the functools module. to use it, you need to introduce it from the functools module.
From functools import performancef = reduce (lambda x, y: x * y, [1, 2, 4]) print (f) # output 8
4. hex (x)
Convert a number to hexadecimal notation
>>> hex(23)'0x17'
5. range (stop), range (start, stop, [step])
Generate an iteratable object
>>> From collections import Iterator >>> isinstance (range (5), Iterator) False >>> from collections import Iterable >>> isinstance (range (5), Iterable) true >>> f. _ next _ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'range' object has no attribute' _ next _ '> for I in f :... print (I )... 01234 # range (x) is an iteratable object, not an iterator
6. isinstance (object, classinfo)
Determine whether a sequence is an iterative object or iterator
7. list ([iterable])
Convert other sequences into a list
>>> List (1, 2, 3, 5) # converts a tuple to a list [1, 2, 3, 4, 5]
8. repr (
Object)
Converting code into a string object is useless. Ignore it here.
9. slice (
Stop), Slice (
Start,
Stop[,
Step])
Slice of Sequence
>>> a = [1,2,3,4,5,6]>>> a[slice(1,3)][2, 3]>>> a[1:3][2, 3]
10. sorted (
Iterable [, key] [, reverse])
>>> Sorted ([, 8]) [2, 3, 5, 6, 8] >>> a =, >>>> sorted (a) # sorted by key by default [1, 3, 6] >>> sorted (. items () # sort by key [(1, 5), (3, 6), (6, 8)] >>> sorted (. items (), key = lambda x: x [1]) # sort by value [(1, 5), (3, 6), (6, 8)]
11. reverse ()
Used for elements in the reverse list. This method does not return values, but sorts the elements in the list in reverse order.
a = [1,2,4,5,3,7] a.reverse()a[7, 3, 5, 4, 2, 1]