10 commonly used built-in functions in Python

Hello everyone, this is Xiao Zhang

In version 3.8, the Python interpreter has a total of nearly 69 built-in functions available for use. With them, coding efficiency can be greatly improved.

image-20210221235544315

Although there are a lot of them, only part of them is used in daily brick-moving. According to the frequency and usage, I will list a few built-in functions that I think are good, and introduce them to you with some examples.

complex()

Returns shaped like a a+bjplurality of incoming parameters are divided into three cases:

  • When the parameter is empty, return0j
  • When the parameter is a string, interpret the string expression as a plural form and return
  • When the parameter is two integers (a, b), return a+bj
  • When the parameter is only an integer a, the imaginary part b defaults to 0, and the function returns a+0j
>>> complex('1+2j')
(1+2j)
>>> complex()
0j
>>> complex(1,2)
(1+2j)
>>> complex(2)
(2+0j)

to you()

  • When no parameters are provided, return a list of names in the current local scope
  • When a parameter is provided, all the attributes contained in the object are returned
>>> class Test:
	def first(self):
		return 1
	def second(self):
		return 2
>>> dir(Test)# 提供参数时
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second']
>>> dir()# 未提供参数时
['Test', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

divmod(a,b)

  • a-represents the dividend, integer or floating point number;
  • b-represents the divisor, integer or floating point;

Calculate the quotient and remainder between a and b according to the division operation, the function returns a tuple (p,q), p represents the quotient a//b, q represents the remaindera%b

>>> divmod(21,4)
(5, 1)
>>> divmod(20.1,3)
(6.0, 2.1000000000000014)

enumerate(iterable,start=0)

  • iterable-an iterable object, list, sequence of tuples, etc.
  • start-count index value, the default initial value is 0

The function returns the enumeration object is an iterator, using the next() method to return the element value in turn, each element exists in the form of a tuple, including a count element (starting at start) and the corresponding element value in iterable;

>>> stu = ['xiao','zhang','li','qian']
>>> enumerate(stu)
<enumerate object at 0x0000025331773F48>
>>> list(enumerate(stu))# 默认start = 0
[(0, 'xiao'), (1, 'zhang'), (2, 'li'), (3, 'qian')]
>>> list(enumerate(stu,start = 1))# 默认start = 1
[(1, 'xiao'), (2, 'zhang'), (3, 'li'), (4, 'qian')]

eval(expression,globals,locals)

  • expression-string expression
  • globals-variable function, global namespace, if provided, it must be in dictionary form; optional parameters
  • locals-variable scope, local namespace, any mapping object if provided; optional parameters

Parse the string expression and return the execution result

>>> eval("2+2")
4
>>> eval("2==2")
True

filter(function,iterable)

  • function – Provide the name of the filter function, return true or false

  • iterable-iterable objects such as lists and tuples

The function returns the elements in iterable that satisfy function as True; assuming there is a list, we only need some of the elements, then we can write a function in advance and filter with the help of filter

>>> num_list = list(range(20))
>>> num_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> def mod_three(num):
	if(num%3==0):
		return True
	else:
		return False

>>> filter(mod_three,num_list)
<filter object at 0x00000253315A6608>
>>> list(filter(mod_three,num_list))
[0, 3, 6, 9, 12, 15, 18]

isinstance(object,classinfo)

  • object-represents a type of object, if it is not of this type, the function always returns False;
  • calssinfo-is a type tuple or a single type;

Judge whether the type of object is one of classinfo or classinfo, and return True or False;

When debugging a Python program, one of the obstacles is that the initial variable does not have a defined type. Therefore, when writing or debugging code, the isinstance() function is often used to determine the type of the variable and help us understand the entire logic of the program to prevent errors.

>>> isinstance(num,str)
False
>>> isinstance(num,int)
True

map(function,iterable,…)

  • function-execute function;
  • iterable-iterable object;

Put each element in iterable into the function function and execute it in turn to get the same iterator with the number of iterable elements;

There can be multiple iterable objects in map(). The parameter in function is the parallel elements in all iterable objects. The final number of iterators is based on the iterable object that provides the least number of elements. When the number is the least The execution stops after all the elements of the iterable object are entered

>>> def fun_a(a,b):
	return a+2*b

>>> num_list1 = [1,2,3,4]
>>> num_list2 = [2,3,4,5]
>>> list(map(fun_a,num_list1,num_list2))
[5, 8, 11, 14]

input()

The function is used for human-computer interaction, read a line of content input from the input terminal, and convert it into a string

>>> s = input('input:')
input:小张Pyhon
>>> s
'小张Pyhon'

zip(*iteables)

  • *iterables-two or more iterable objects

The elements in all iterable objects are aggregated element by element in the order of the parameters, and finally an iterator is obtained. Each element in the iterator is a tuple of n elements, and n represents the number of input iterable parameters in the function

>>> num_list1 = [1,2,3,4]
>>> num_list2 = [2,3,1,2]
>>> list(zip(num_list1,num_list2))
[(1, 2), (2, 3), (3, 1), (4, 2)]

The zip() function is equivalent to

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

In addition to the 10 listed above, there are 59 other built-in functions. Those who want to know can click on the original text below to read. It is very useful for Python developers to master these built-in functions. On the one hand, it can improve coding efficiency. Aspects can also improve code conciseness; in a certain aspect, although functions are not as powerful as third-party library functions, they cannot be underestimated.

Okay, the above is the entire content of this article, and finally thank you all for reading, see you in the next issue~

Guess you like

Origin blog.csdn.net/weixin_42512684/article/details/114199190