10 Python built-in functions you must know

1. reduce()

   reduce() is a function under the functools module. It receives two parameters, one is a function object and the other is an iterative object (such as list). Each time, reduce will act the next element in the iterative object on the function for cumulative calculation, and finally get a value.

Take an example and you'll see

# 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("result:", result) 

output

1 + 2 = 3  
3 + 3 = 6  
6 + 4 = 10  
Result: 10 

   execution process: take the first two numbers in the list as the parameters of the function add for the first time, take the return value of the previous function add and the third number in the list as the parameters for the second time, and so on, and finally get a value. This is the role of reduce. It's a bit like the unity of all things.

    of course, if you just calculate the sum of the elements in the list, you don't have to deal with it with reduce around such a big bend. You can solve it directly with the sum function.

result = sum([1, 2, 3, 4]) 

    if you are calculating the product of elements in the list, python does not have a built-in function to calculate it directly. At this time, we can use reduce to deal with it

def mul(a, b):  
    return a * b  
result = reduce(mul, [1, 2, 3, 4])  
print("result:", result) 

output

Result: 24
Or use lambda anonymous functions

result = reduce(lambda a, b: a * b, [1, 2, 3, 4]) 

You can even directly use the multiplication operator function under the operator module

from operator import mul  
result = reduce(mul, [1, 2, 3, 4]) 
print("result:", result) 

Finally, you will find that there are many solutions, but we should remember the sentence in python Zen:

There should be one-- and preferably only one --obvious way to do it.

Do something in the most appropriate way

2. split()

   split receives a parameter for cutting strings into lists. For example, if an English string is cut according to spaces, the number of words can be counted,

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 iteratable objects. Its usage scenario generally appears when you need to obtain the subscript position of the list. We know that when you directly iterate the list with the for loop, you can't get the element subscript position, but enumerate 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 

Using the enumerate function makes it 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 function corresponding to the reduce function. The idea of Google's map/reduce framework is actually drawn from these two functions. The map function is used to map a list into a new list through function processing. For example, square each element of the list, convert the list element into a string, 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, the map function can also accept multiple list parameters, making it possible to combine multiple lists into one list. For example, add the elements at the same position of the 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 is usually used by the user dynamically or the values of some attributes under an object. See an example:

class Foo:  
    def __init__(self):  
        self.a = 10  
foo = Foo()  
a = getattr(foo, "a")  
print(a) 

output

  1. 10

  you may ask, can't I get the value of the a attribute directly from foo.a? Normally, that's right. If you don't know what attribute value to obtain under what circumstances, getattr can come in handy. Beginners may not experience it. When you try to write some framework level code, you should remember that such a function can be used.

6. slice

slice is a slicing function. You may have used slicing operations to obtain a subset of the list through slicing, for example:

s = [1,2,3,4] 
 
>>> s[1:3]  # Gets a sublist consisting of elements between the 1st and 3rd in the list s 

"1:3" is the abbreviation of slice(1:3) function. The former is like a syntax sugar

s = [1, 2, 3, 4]  
print(s[slice(1, 3)]) 

    usually in the process of practical application, you can write sugar directly. There is no need to slice with slice function, but you should at least know how slice is used.

7. sorted()

   sorted function should be a high-frequency function in daily code. It is used to sort list and other iteratable objects. It will not change the order of the original list, but return a new list. The default is in ascending order

nums = [4, 5, 6, 3, 1]  
print(sorted(nums)) 

output

[1, 3, 4, 5, 6] 

If you want to arrange in descending order, you need to specify the second parameter: reverse=True

nums = [4, 5, 6, 3, 1]  
print(sorted(nums, reverse=True))  # [6, 5, 4, 3, 1] 

   the sorted function is far more powerful than that, because you can also customize the sorting rules. For example, the comparison is a user-defined class Student. I need to sort according to the age in the Student. At this time, we need to customize the sorting factor function

def my_sort_key(s):  
    return s.age  
class Student:  
    def __init__(self, age):  
        self.age = age  
    def __str__(self): 
        return f"Student({self.age})"  
s1 = Student(12)  
s2 = Student(2)  
s3 = Student(30)  
new_list = (sorted([s1, s2, s3], key=my_sort_key))  
for i in new_list:  
    print(i) 

Output:

Student(2)  
Student(12)  
Student(30) 

8. format

   format function used to be the most commonly used function for string formatting, and it is also very simple to use. However, since the emergence of f string, the function of format has been gradually replaced, but the application scenario of this function can still be seen before 3.6.

s = "{} is first name"  
print(s.format("liu")) 

  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

s = "{first_name} is first name"  
print(s.format(first_name="liu")) 

9. join()

   join is also a commonly used built-in function, which can convert the list object into a string using the specified character as the connection between elements.

words = ['python', 'is', 'the', 'best', 'programming', 'language']  
print(" ".join(words)) # Connect python is the best programming language with spaces 

10. type

   type is the most difficult built-in function in python. Novices may think that type is a type used to view an object, for example:

print(type(10)) # <class 'int'>  
print(type([])) # <class 'list'>  
print(type("s"))#  <class 'str'> 

   another function of it is to use type to create classes. Generally, we use the keyword class to define a class, and type can also be used to create classes

>>> Person = type("Person", (), {"live":True})  
>>> Person  
<class '__main__.Person'> 

   the first parameter Person is the name of the class, the second parameter is used to specify who the parent class is, and the third parameter is the class attributes of this class. The above code is equivalent to:

>>> class Person:  
...     live = True  
...  
>>> Person  
<class '__main__.Person'> 

  creating a type function such as Person is actually a thing called "metaclass". About metaclasses, you can even use a whole article to explain it. Fortunately, I introduced it in the previous article. If you are interested, you can check the previous article called what is Python metaclasses. Metaclasses are often used when writing some frameworks. For example, when you press the source code of sqlalchemy, you will find that there are a lot of scenarios in which metaclasses are used.

Hongmeng official strategic cooperation and Co Construction -- HarmonyOS technology community

  experience in software testing, interface testing, automation testing, continuous integration and interview. If you are interested, you can go to 806549072. There will be irregular sharing of test data in the group. There will also be technology giants to exchange technology with peers in the industry

Keywords: Python Pycharm crawler

Added by tharagleb on Thu, 07 Oct 2021 23:00:23 +0300