Python - Common built-in functions

map

map() will map the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

Return the list in Python 2 and the iterator in Python 3.

def square(x):
    return x ** 2


print(list(map(square, [1, 2, 3, 4])))
---------------------
1 4 9 16 

#Use anonymous functions
print(list(map(lambda x:x**2, [1, 2, 3, 4])))
-------------
1 4 9 16 

# Two lists are provided to add the list data at the same location
print(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
-------------
[3, 7, 11, 15, 19]

filter

The filter() function is used to filter the sequence, filter out the elements that do not meet the conditions, and return a new list composed of qualified elements.

The receives two parameters. The first is a function and the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment, and then returns True or False. Finally, the element that returns True is placed in the new list.

List is returned in python2 and iterator is returned in python3

def is_odd(n):
    return n % 2 == 1


newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
---------------
[1, 3, 5, 7, 9]

zip

The zip() function is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return a list composed of these tuples.

If the number of elements of each iterator is inconsistent, the length of the returned list is the same as that of the shortest object. The tuple can be decompressed into a list by using the * operator.

Learn about the difference between the zip method in Python 2 and python 3: in Python 3 To reduce memory in X, zip() returns an object. To display the list, you need to manually convert the list().

a = [1, 2, 3]
b = [4, 5, 6]
c = [7,8,9,10]

res1 = zip(a, b)
res2 = zip(a, c)
print(list(res1))
print(list(res2))
----------------
[(1, 4), (2, 5), (3, 6)]
[(1, 7), (2, 8), (3, 9)]

next

next() returns the next item of the iterator.

The next() function is used with the iter() function that generates the iterator.

# First get the Iterator object:
it = iter([1, 2, 3, 4, 5])
# Cycle:
while True:
    try:
        # Get the next value:
        x = next(it)
        print(x)
    except StopIteration:
        # Exit the loop when StopIteration is encountered
        break

Understanding: if the second parameter is passed in, after obtaining the last element, the next time will return the default value without throwing StopIteration:

it = iter([1, 2, 5, 4, 3])
while True:
    x = next(it, 'a') # You can set a final default value when next
    print(x)
    if x == 'a':
        break
------------------------
1
2
5
4
3
a

hash

hash() is used to get the hash value of an object (string or value, etc.).

The hash() function can be applied to numbers, strings and objects, not directly to list s, set s and dictionaries.

When hash() is used on an object, the result is related not only to the content of the object, but also to the id() of the object, that is, the memory address.

hash('test') # character string
----------
2314058222102390712

hash(1) # number
--------
1

hash(str([1,2,3]))  # aggregate
------------------
1335416675971793195

hash(str(sorted({'1':1}))) # Dictionaries
---------------
7666464346782421378

help

The help() function is used to view a detailed description of the purpose of a function or module

>>>help('sys')             # View help for sys module
......Show help
 
>>>help('str')             # View help for str data types
......Show help
 
>>>a = [1,2,3]
>>>help(a)                 # View list help information
......Show help
 
>>>help(a.append)          # Displays help for the append method of the list
......Show help

id

The id() function returns the unique identifier of the object. The identifier is an integer.

The id() function in CPython is used to get the memory address of the object.

name = 'yang'
print(id(name))
---------------
2541526569288

enumerate

The enumerate() function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list the data and data subscripts at the same time. It is generally used in the for loop.

list1 = iter([1,2,3,4,5])
for index,value in enumerate(list1):
    print(index,value)
-----------------------
0 1
1 2
2 3
3 4
4 5

reduce

The reduce() function accumulates the elements in the parameter sequence.

The function performs the following operations on all data in a data set (linked list, tuple, etc.): first operate the first and second elements in the set with the function (with two parameters) passed to reduce, and then operate with the third data with the function function, and finally get a result. Just look at the following example

from functools import reduce

print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))
---------------------
15

eval

The eval() function executes a string expression and returns the value of the expression. The dictionary format string stored in the file can also be converted by Eval, but it is generally not used, because we can use json or pickle module

x = 3
print(eval('10-x'))
------
7

Tags: Python

Posted by austrainer on Wed, 04 May 2022 21:33:38 +0300