There are many built-in functions in Python that are not as well known as print, but they are surprisingly powerful and can greatly improve code efficiency when used properly.

This time I’ll take a look at eight useful python built-in functions.

1, the set ()

The set() function comes in handy when you need to de-redo a list.

obj = ['a'.'b'.'c'.'b'.'a']
print(set(obj))'b'.'c'.'a'}
Copy the code

Set ([iterable]) is used to create a collection of elements that are unordered and not repeated.

After the collection object is created, the union, intersection, and difference set functions can also be used.

A = set('hello')
B = set('world') a.nion (B) # union, {'d'.'e'.'h'.'l'.'o'.'r'.'w'} a.int (B) #'l'.'o'} a value (B) {'d'.'r'.'w'}
Copy the code

2, the eval ()

Someone asked earlier how to write a four-way algorithm in Python, input a string formula, and produce the result directly.

This is easy to do with eval() :

Eval (str_expression) converts a string into an expression and executes it.

a = eval('[1, 2, 3]')
print(type(a) # output: <class'list'>

b = eval('Max (, four, five [2])')
print(b) # Output:5
Copy the code

3, sorted ()

In data processing, we often use sorting operations, such as sorting elements in lists, dictionaries, and tuples backwards and forwards.

This is where sorted() comes in, which sorts any iterable and returns a list.

To upgrade a list:

a = sorted([2.4.3.7.1.9])
print(a) # output:1.2.3.4.7.9]
Copy the code

Reverse operation on tuples:

sorted((4.1.9.6),reverse=True)
print(a) # output:9.6.4.1]
Copy the code

Use the key argument to sort by string length according to custom rules:

chars = ['apple'.'watermelon'.'pear'.'banana']
a = sorted(chars,key=lambda x:len(x))
print(a) # output:'pear'.'apple'.'banana'.'watermelon']
Copy the code

Sort a list of tuples according to custom rules:

tuple_list = [('A'.1.5), ('B'.3.2), ('C'.2.6)]
# key=lambda x: x[1] a = sorted(tuple_list, key=lambda x: x[1])
print(a) # output:'A'.1.5), ('C'.2.6), ('B'.3.2)]
Copy the code

4, the reversed ()

The reversed() function will help you if you need to reverse elements of a sequence.

Reversed () takes a sequence, reverses the elements in the sequence, and ultimately returns an iterator.

a = reversed('abcde')
print(list(a))'e'.'d'.'c'.'b'.'a']

b = reversed([2.3.4.5])
print(list(b))5.4.3.2]
Copy the code

5, the map ()

When you do text processing, let’s say you want to capitalize every word in a sequence.

At this point you can use the map() function.

chars = ['apple'.'watermelon'.'pear'.'banana']
a = map(lambda x:x.upper(),chars)
print(list(a))'APPLE'.'WATERMELON'.'PEAR'.'BANANA']
Copy the code

Map () maps the specified sequence based on the provided function and returns an iterator.

That is, the map() function will process each element in the sequence in the specified way and return the sequence.

For example, square each number in a list:

nums = [1.2.3.4]
a = map(lambda x:x*x,nums)
print(list(a))1.4.9.16]
Copy the code

6, the reduce ()

We talked about squaring each number in the list using the map() function.

So IF I want to multiply each element of this list, how do I do that?

This is where the reduce() function is used.

from functools import reduce
nums = [1.2.3.4]
a = reduce(lambda x,y:x*y,nums)
print(a) # Output24
Copy the code

Reduce () accumulates the elements in the parameter sequence.

The first and second elements perform function operations first, and then the generated result performs function operations with the third element, and so on, and finally generates the cumulative operation results of all elements.

Another example is concatenating letters into strings.

from functools import reduce
chars = ['a'.'p'.'p'.'l'.'e']
a = reduce(lambda x,y:x+y,chars)
print(a) # Output: AppleCopy the code

You may have noticed that the reduce() function is no longer a built-in function in python3, but has been migrated to the functools module.

The reduce() function is highlighted here because it is so important.

7, the filter ()

I have a list of numbers, and I want to get rid of even numbers. How do I do that?

nums = [1.2.3.4.5.6]
a = filter(lambda x:x%2! =0,nums)
print(list(a))1.3.5]
Copy the code

The filter() function is an easy way to filter a sequence, filter out elements that do not meet the criteria, and return an iterator object.

The filter() function is similar to the map() and reduce() functions in that it maps each element in the sequence to the function and returns the result.

Let’s try again how to pick out from many words the one that contains the letter W.

chars = chars = ['apple'.'watermelon'.'pear'.'banana']
a = filter(lambda x:'w' in x,chars)
print(list(a))'watermelon']
Copy the code

8, enumerate ()

To do this, print out each element in the sequence with its ordinal number, using enumerate().

chars = ['apple'.'watermelon'.'pear'.'banana']
for i,j in enumerate(chars):
    print(i,j)

' '0 ripe apple 1 ripe 2 pear 3 banana' '
Copy the code

The enumerate() function is used to order the contents of a sequence and return iterators.

In another example, annotating a string returns each letter and its index.

a = enumerate('abcd')
print(list(a))0.'a'), (1.'b'), (2.'c'), (3.'d')]
Copy the code

Machine Learning Online Manual Deep Learning online Manual AI Basics download (PDF updated to25Set) site QQ group1003271085To join the wechat group, please reply to "add group" to get a discount station knowledge planet coupon, please reply to "knowledge planet" like the article, click on itCopy the code