10 built in functions that you must know to use Python
- 2021-12-04 10:24:29
- OfStack
1. reduce()
reduce()
Yes
functools
A function under the module that takes two arguments, one is a function object and one is an iterable object (such as list),
reduce
Each time, the next element in the iteration object will be applied to the function for cumulative calculation, and finally a value will be obtained.
Look at an example and you will understand that creating a function:
# Create function
def add(a, b):
result = a + b
print(f"{a} + {b} = {result}")
return result
from functools import reduce
result = reduce(add, [1, 2, 3, 4])
print(" Results: ", result)
Output:
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
Results: 10
Execution procedure: fetch the first two numbers in the list as functions for the first time
add
For the second time, take the return value of the previous function add and the third number in the list as parameters, and so on, and finally get a value. This is what it is
reduce
The role of. It's a bit like everything is one.
Of course, if you just calculate the sum of the elements in the list, you don't have to go around such a big bend
reduce
To deal with, directly use sum function can be solved.
result = sum([1, 2, 3, 4])
If you are calculating the product of elements in a list,
python
There is no built-in function to calculate directly, so we can borrow it at this time
reduce
To deal with
def mul(a, b):
return a * b
result = reduce(mul, [1, 2, 3, 4])
print(" Results: ", result)
Output:
Results: 24
Or use
lambda
Anonymous function
result = reduce(lambda a, b: a * b, [1, 2, 3, 4])
You can even use the multiplication operator function under the operator module directly
from operator import mul
result = reduce(mul, [1, 2, 3, 4])
print(" Results: ", result)
In the end, you will find that there are actually many solutions, but we should remember that
python
The sentence in Zen:
There should be one-- and preferably only one --obvious way to do it.
Do one thing in the most appropriate way
2. split()
functools
0
Receive a parameter, used to cut the string into a list, for example, a segment of English string can be cut according to the space to count the number of words,
words = "python is the best programming language"
wordswords = words.split(" ")
print(words)
Output:
['column1', 'column2', 'column3']
3. enumerate()
enumerate
Function is used to iterate the list and other iterative objects. Its usage scenario 1 appears when you need to get the subscript position of the list. We know that when you iterate the list directly with for loop, you can't get the subscript position of the element.
enumerate
You can get it, otherwise you have to define an index variable yourself.
words = ['python', 'is', 'the', 'best', 'programming', 'language']
index = 0
for w in words:
print(index, w)
index += 1
0 python
1 is
2 the
3 best
4 programming
5 language
Use
enumerate
Function, it is more elegant to handle
for index, w in enumerate(words):
print(index, w)
0 python
1 is
2 the
3 best
4 programming
5 language
4. map()
map is a
reduce
Function corresponds to the function,
Google
Adj.
map/reduce
In fact, the idea of framework is borrowed from these two functions. The map function is used to map a list to a new list through function processing. For example, square each element of the list, convert the list elements into strings, and get a new list.
result = map(lambda x: str(x), [1, 2, 3, 4])
print(list(result))
result = map(lambda x: x * x, [1, 2, 3, 4]))
print(list(result))
Output:
['1', '2', '3', '4']
[1, 4, 9, 16]
In addition,
map
The function can also accept multiple list parameters, making it possible to merge multiple lists into one list, for example, adding elements in the same position of two lists to get a new list
def merge(x, y):
return x + y
result = map(merge, [1, 2, 3], [3, 2, 1])
print(list(result))
Output:
[4, 4, 4]
5. getattr()
getattr()
Returns the value corresponding to the object attribute, and accepts two parameters, the first is the object, and the second is the attribute name. This function usually uses the value of some attributes under the user or an object. See the example:
result = sum([1, 2, 3, 4])
0
Output:
10
You may ask, I directly
foo.a
Can't you get the value of a attribute? Normally, this is true. If you don't know under what circumstances, you want to get the value of what attribute. At this time,
getattr
You can come in handy. Beginners may not experience it. When you try to write some framework-level code, you should remember that there are such functions to use.
6. slice
slice
Is a slicing function. You may have used slicing operations to get a subset of the list by slicing, for example:
result = sum([1, 2, 3, 4])
1
"1:3"
It is just that
slice(1:3)
Function, the former is like grammatical sugar
result = sum([1, 2, 3, 4])
2
Usually, in the practical application process, it is OK to write it directly with grammar sugar. There is no need to slice it with slice function, but you should at least know how to use slice.
7. sorted()
sorted
Function should be a high-frequency function in daily code, which is used to sort iterative objects such as lists. It will not change the order of the original list, but return a new list. By default, it is arranged in ascending order
nums = [4, 5, 6, 3, 1]
print(sorted(nums))
Output:
[1, 3, 4, 5, 6]
If you want to sort in descending order, you need to specify the second parameter:
reverse=True
result = sum([1, 2, 3, 4])
4
sorted
Function is more powerful than that, because you can also customize collations, for example, participating in comparison is a custom class
Student
I need to follow
Student
The age age in it is sorted, and we need to customize the sorting factor function at this time
result = sum([1, 2, 3, 4])
5
Output:
Student(2)
Student(12)
Student(30)
8. format
format
Function was once the most commonly used function for string formatting, and it is also very simple to use, but since f string appeared,
format
The function of is gradually replaced, but the application scenario of this function can still be common before 3.6.
result = sum([1, 2, 3, 4])
6
If you need more placeholders and can't figure out the order, you can give each placeholder a name, so you can't shoot the right position
result = sum([1, 2, 3, 4])
7
9. join()
add
1
It is also a commonly used built-in function, which can use the specified characters as the connection between elements of the list object and convert it into a string.
words = ['python', 'is', 'the', 'best', 'programming', 'language']
print(" ".join(words)) # Connect with spaces python is the best programming language
10. type
add
2
I think so
python
One of the most difficult built-in functions to understand. Beginners may think that type is a built-in function to see what the type of an object is, such as:
result = sum([1, 2, 3, 4])
9
One of its other functions is to use type to create a class. In general, we use the keyword class to define a class, and type can also be used to create a class
>>> Person = type("Person", (), {"live":True})
>>> Person
<class '__main__.Person'>
The first parameter
Person
Is the name of the class, the second parameter specifies who the parent class is, and the third parameter is what the class attributes of this class have. The above code is equivalent to:
>>> class Person:
... live = True
...
>>> Person
<class '__main__.Person'>
Create
Person
This kind of type function is actually a thing called "metaclass". The metaclass can even be explained in the whole article. Fortunately, I have introduced it in the previous article. If you are interested, you can see the article called Python metaclass written before. Metaclass is used more when writing 1 frame, for example, you click
sqlalchemy
Source code, you will find that there are a lot of scenarios using metaclasses.