20 “Naughty Operations” in Python that will make you regret seeing each other too late

Today I would like to share with you twenty “sexy operations” that novices in Python programming must know. They are used very frequently! Remember to like and collect! Without further ado, let’s get to the point!

1. List comprehension

Create a list using list comprehensions.

>>> [n*10 for n in range(5)]
[0, 10, 20, 30, 40]

2. Exchange variables

One line of code swaps the values of two variables.

>>> m, n = 1, 2
>>> m, n = n, m
>>> m
2
>>> n
1

3. Continuous comparison

Chained comparison operators.

>>> m, n = 3, 'c'
>>> 1 < m < 5
True
>>> 'd' < n < 'f'
False

4. Sequence slicing

Quickly obtain sequence fragments through slicing.

>>> lst = [1, 2, 3, 4, 5]
>>> lst[:3] # Take the first three numbers
[1, 2, 3]
>>> lst[::-1] # Reverse order
[5, 4, 3, 2, 1]
>>> lst[::2] # step size is 2
[1, 3, 5]
>>> lst[::-2] # Reverse step size is 2
[5, 3, 1]

5. Quickly add and delete sequences in slices

Replaces the value of a sequence fragment by slicing.

>>> lst = [1, 2, 3, 4, 5]
>>> lst[1:3] = []
>>> lst
[1, 4, 5]
>>> lst[1:3] = ['a', 'b', 'c', 'd']
>>> lst
[1, 'a', 'b', 'c', 'd']

6.%timeit calculates running time

Calculate the time it takes to create a list 10,000 times with a list comprehension.

%timeit -n 10000 [n for n in range(5)]

# 2.41 μs ± 511 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

7. Ternary expression

Get the larger value among m, n.

>>> m = 4
>>> n = 2
>>> if m > n:
        print('m')
else:
        print('n')

m
>>> 'm' if m > n else 'n'
'm'

There is also a relatively rare way of writing.

>>> m = 4
>>> n = 2
>>> ("n", "m")[m > n]
'm'

Format: (, )[condition]

8. Unpack

Iterable objects all support unpacking.

>>> a, b, *c = [1, 2, 3, 4]
>>>a
1
>>> b
2
>>>c
[3, 4]
>>> print(*range(3))
0 1 2

9.lambda anonymous function

The lambda function can receive any number of parameters (including optional parameters) and return a single expression value. A lambda function cannot contain commands, only an expression.

>>> def func(x, y):
return x*y

>>> func(2, 3)
6
>>> func = lambda x, y: x * y
>>> func(2, 3)
6

10.map sequence mapping

Call the specified function on each element in the sequence and return an iterator.

>>> def func(x):
return x**2

>>> list(map(func, [1,2,3]))
[1, 4, 9]

Use lambda expressions.

>>> list(map(lambda x: x ** 2, [1, 2, 3]))
[1, 4, 9]

11.filter filter sequence

Filter out elements that do not meet the conditions and return an iterator.

>>> def func(x):
return x % 3 == 0
  
>>> list(filter(func, [1, 2,3]))
[3]

Use lambda expressions.

>>> list(filter(lambda x: x % 3 == 0, [1, 2, 3]))
[3]

12. Obtain sequence combination

Get the result of pairwise combination of each element of two sequences.

>>> list1 = ['a', 'b']
>>> list2 = ['1', '2']
>>> [(m, n) for m in list1 for n in list2]
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]
>>> from itertools import product
>>> list(product(list1, list2))
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]

13. Randomly select sequence elements

Randomly select an element from the sequence.

>>> from random import choice
>>> lst = [1, 2, 3, 4]
>>>choice(lst)
3

Randomly select multiple elements from a sequence (Repeatable). The k value specifies the number.

>>> from random import choices
>>> lst = [1, 2, 3, 4]
>>> choices(lst, k=3)
[4, 3, 4]

Randomly select multiple elements from the sequence (non-repeating). The k value specifies the number.

>>> from random import sample
>>> lst = [1, 2, 3, 4]
>>> sample(lst, k=3)
[4, 3, 2]

14. Sequence element count

Count the number of occurrences of each element in the sequence.

>>> from collections import Counter
>>> s = 'python + py'
>>> counter = Counter(s)
>>> counter
Counter({
 'p': 2, 'y': 2, 't': 1, 'h': 1, 'o': 1, 'n': 1, ' + ': 1})

The returned result is similar to a dictionary, and you can use dictionary related methods.

>>> counter.keys()
dict_keys(['p', 'y', 't', 'h', 'o', 'n', ' + '])
>>> counter.values()
dict_values([2, 2, 1, 1, 1, 1, 1])
>>> counter.items()
dict_items([('p', 2), ('y', 2), ('t', 1), ('h', 1), ('o', 1), ('n', 1) , (' + ', 1)])

Count the two elements that appear the most.

>>> counter.most_common(2)
[('p', 2), ('y', 2)]

15. Dictionary sorting

Dictionaries are sorted in descending order by key.

>>> dic = {
 'd': 2, 'c': 1, 'a': 3, 'b': 4}
>>> sort_by_key = sorted(dic.items(), key=lambda x: x[0], reverse=False)
>>> {
 key: value for key, value in sort_by_key}
{
 'a': 3, 'b': 4, 'c': 1, 'd': 2}

The dictionary is sorted by value in descending order.

>>> dic = {
 'd': 2, 'c': 1, 'a': 3, 'b': 4}
>>> sort_by_value = sorted(dic.items(), key=lambda x: x[1], reverse=False)
>>> {
 key: value for key, value in sort_by_value}
{
 'c': 1, 'd': 2, 'a': 3, 'b': 4}

16. Dictionary merging

>>> dict1 = {
 'name': 'Shizuka', 'age': 18}
>>> dict2 = {
 'name': 'Shizuka', 'sex': 'female'}
  1. update() updates the dictionary.
>>> dict1.update(dict2)
>>> dict1
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}
  1. dictionary comprehension
>>> {
 k: v for dic in [dict1, dict2] for k, v in dic.items()}
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}
  1. Element splicing
>>> dict(list(dict1.items()) + list(dict2.items()))
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}
  1. chain() can connect sequences and return an iterable object.
from itertools import chain
>>> dict(chain(dict1.items(), dict2.items()))
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}
  1. collections.ChainMap can take multiple dictionaries or maps and merge them.
>>> from collections import ChainMap
>>> dict(ChainMap(dict2, dict1))
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}
  1. In Python 3.5 and above, merging can be done through dictionary unpacking.
>>> {
 **dict1, **dict2}
{
 'name': 'Shizuka', 'age': 18, 'sex': 'female'}

17.zip packaging

zip() packs the corresponding elements in the sequence into tuples, and then returns an iterator composed of these tuples.

If the number of elements in the sequence is inconsistent, the length of the returned list is the same as the shortest object.

>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list3 = ['a', 'b', 'c', 'd']
>>> res = zip(list1, list2)
>>>res
<zip object at 0x0000013C13F62200>
>>> list(res)
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(list2, list3))
[(4, 'a'), (5, 'b'), (6, 'c')]

18.enumerate traversal

The enumerate function can combine iterable objects into an index sequence, so that the index and the corresponding value can be obtained at the same time when traversing.

>>> lst = ['a', 'b', 'c']
>>> for index, char in enumerate(lst):
print(index, char)

\t
0a
1b
2c

19.any() & amp; all()

any(iterable)

any

all(iterable)

all
>>> any('')
False
>>> any([])
False
>>> any([1, 0, ''])
True
>>> any([0, '', []])
False
>>> all([])
True
>>> all([1, 0, ''])
False
>>> all([1, 2, 3])
True

20. Use ** instead of pow

To find x raised to the y power, use ** which is faster.

%timeit -n 10000 c = pow(2,10)
# 911 ns ± 107 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit -n 10000 c = 2 ** 10
# 131 ns ± 46.8 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

This is what I want to share today, remember to like it~Thanks in advance

About Python technical reserves

Learning Python well is good whether you are getting a job or doing a side job to make money, but you still need to have a learning plan to learn Python. Finally, we share a complete set of Python learning materials to give some help to those who want to learn Python!

Includes: Python activation code + installation package, Python web development, Python crawler, Python data analysis learning and other tutorials. Let you learn Python systematically from scratch!

1. Python learning outline

The technical points in all directions of Python are organized to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2. Essential development tools for Python

3. Introductory learning video

4. Practical cases

Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned to practice. At this time, you can learn from some practical cases.

5. Python side job part-time and full-time routes

The above-mentioned complete version of the complete set of Python learning materials has been uploaded to the CSDN official. If necessary, you can scan the CSDN official certification QR code below on WeChat to get it

[[CSDN gift package: “Python part-time resources & full set of learning materials” free sharing]](Safe link, Feel free to click)