Do you know this 25 Python coding skills?

Do you know this 25 Python coding skills? In this post, I have categorized 25 python coding skills, which are really efficient/colleague chat topics, you can bookmark them.

Python coding skills

Do you know this 25 Python coding skills?
Do you know this 25 Python coding skills?

1. In-situ exchange

Python provides an intuitive way to assign and exchange (variable values) in a line of code

x, y = 10, 20
print(x, y)
 
x, y = y, x
print(x, y)
 
#1 (10, 20)
#2 (20, 10)

Python coding skills

Principle: The right side of the assignment forms a new tuple, and the left side immediately unpacks that (unquoted) tuple to the variables and . Once the assignment is completed, the new tuple becomes an unreferenced state and is marked for garbage collection, and finally the exchange of variables is completed.

2. chain comparison operators

Python does not need to write many conditions one by one, and comparison operators can aggregate.

n = 10
result = 1 < n < 20
print(result)
 
# True
 
result = 1 > n <= 9
print(result)
 
# False

Python coding skills

3. ternary operator for conditional assignment

The ternary operator is an if-else statement that is a shortcut of the conditional operator: [expression is true return value] if [expression] else [expression is false return value]

Here is an example that you can use to make the code compact and concise. The following statement says “If y is 9, assign 10 to x, otherwise assign the value 20”.

x = 10 if (y == 9) else 20

Python coding skills

 In the list comprehension:

[m**2 if m > 10 else m**4 for m in range(50)]

Python coding skills

Determine the minimum value:

def small(a, b, c):
return a if a <= b and a <= c else (b if b <= a and b <= c else c)

Python coding skills

In the class:

x = (classA if y == 1 else classB)(param1, param2)

Python coding skills

4. multi-line string

This is much more convenient than c. It’s really uncomfortable to put a newline character in c and add an escape.

a='''dvfssd
fsdfdsfsd
dsdsfbfdfasf
afasfaf'''
print(a)

Python coding skills

5. in judgment

Can be used directly to determine whether a variable is in the list

We can use the following methods to verify multiple values:

if m in [1,3,5,7]:

Instead of:

if m==1 or m==3 or m==5 or m==7:

6. four ways to flip strings/lists

# Flip the list itself

testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]

Python coding skills

# Flip and iterate the output in a loop

for element in reversed([1,3,5]):
    print(element)
#1-> 5
#2-> 3
#3-> 1

Python coding skills

# One line of code to reverse the string

"Test Python"[::-1]
 
 
 
#response “nohtyP tseT”

Python coding skills

# Use slice to flip list

[1, 3, 5][::-1]
 
 
#output [5,3,1]。

Python coding skills

7. initialize multiple variables at once

Can be assigned directly:

a,b,c,d=1,2,3,4

You can use the list:

List = [1,2,3]
x,y,z=List
print(x, y, z)
#-> 1 2 3

Python coding skills

(The number of elements should be the same as the length of the list)

8. Print module path

import socket
print(socket)
#<module 'socket' from '/usr/lib/python2.7/socket.py'>
 

9. dictionary derivation

Python not only uses comprehensions for lists, but also for dictionaries/sets

#list
l=[[0 for i in range(4)] for i in range(4)]#Generate a two-dimensional list
print(l)
#  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Python coding skills

testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}
 
print(testSet)
print(testDict)
 
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Python coding skills

10. splicing strings

As we all know, strings in python can be added:

a="i "
b="love "
c="you"
print(a+b+c)

All elements in the concatenated list are a string

l=['a','b','c']
print(''join(l))
#Split by the character to the left of join

Python coding skills

11. circular enumeration index

list = [10, 20, 30]
for i, value in enumerate(list):
    print(i, ': ', value)
 
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30

Python coding skills

It’s easy to find the subscripts and corresponding elements

12. return multiple values

Not many programming languages ​​support this feature, but methods in Python do (can) return multiple values

def a():
    return 1,2,3,4,5

13. Open file sharing

Python allows running an HTTP server to share files from the root path. Here is the command to start the server:

python3 -m http.server

Python coding skills

The above command will start a server at the default port which is 8000. You can pass a custom port number to the above command as the last parameter.

14. Debug script

We can set breakpoints in Python scripts with the help of the module, for example:

import pdb
pdb.set_trace()

15. direct iterative sequence elements

For sequences (str, list, tuple, etc.), iterating the sequence elements directly is faster than iterating the index of the elements.

>>> l=[0,1,2,3,4,5]
>>> for i in l:
	print(i)
#fast
>>> for i in range(len(l)):
	print(l[i])
#slow

Python coding skills

16. clever use of the else statement (important)

Python’s else clause can be used not only in if statements, but also in statements such as for, while, and try. This language feature is not a secret, but it has not been taken seriously.

for:

l=[1,2,3,4,5]
for i in l:
    if i=='6':
        print(666)
        break
else:
    print(999)

If this is not achieved, we can only set a variable to record:

l=[1,2,3,4,5]
a=1
for i in l:
    if i=='6':
        print(666)
        a=0
        break
if a:
    print(999)

Python coding skills

while and for are similar

Take a look at try:

try:
    a()
except OSError:
    #Statement 1
else:
    #Statement 2

Run the else block only when no exception is thrown in the try block.

To summarize the else:

for:

  Run the else block only when the for loop is finished (that is, the for loop is not terminated by the break statement).

while:

  Run the else block only when the while loop exits because the condition is false (that is, the while loop is not terminated by the break statement).

try:

  Run the else block only when no exception is thrown in the try block.

That is, if an exception or a return, break, or continue statement causes control to jump outside the main block of the compound statement, the else clause will also be skipped.

 According to the normal understanding, it should be “either run this loop or do that.” However, in a loop, the semantics of else is exactly the opposite: “Run this loop, and then do that thing.”

17. The usage and function of except

try/except: Catch the exception caused by PYTHON itself or in the process of writing the program and recover

except: catch all other exceptions

except name: only catch specific exceptions

except name, value: capture exceptions and extra data (example)

except (name1,name2) catch the listed exception

except (name1,name2),value: catch any of the listed exceptions and obtain additional data

else: run if no exception is raised

finally: always run this code

18. Python introspection

This is also the sturdy feature of python. Introspection is the type of object that a program written in an object-oriented language can know at runtime. A simple sentence is the type of object that can be obtained at runtime. For example, type(), dir(), getattr (), hasattr(), isinstance().

19. python container

List: Variable elements (any data type), ordered (indexable), append/insert/pop;

Tuple: The element is immutable, but the variable element in the element is variable; ordered (indexable); and the tuple can be hashed, for example, as a dictionary key.

Collection: unordered (not to be indexed), mutually different

Dictionary: unordered, key-value pairs (key: value), the key is unique and cannot be repeated

20. map()

map()The function receives two parameters, one is a function, and the other is Iterableto mapapply the passed function to each element of the sequence in turn, and return the result as a new one Iterator. (Key understanding)

For example, for example, we have a function f(x)=x2 [1, 2, 3, 4, 5, 6, 7, 8, 9]. To apply this function to a list , it can be map()implemented as follows:

>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Python coding skills

map()As a high-order function, it actually abstracts the rules of operation. Therefore, we can not only calculate simple f(x)=x2, but also calculate arbitrarily complex functions. For example, convert all numbers in this list into strings:

>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

21. reduce

reduceTo apply a function to a sequence [x1, x2, x3, …], this function must receive two parameters, reduceand continue the result with the next element of the sequence for cumulative calculation

Simple example:

>>> from functools import reduce
>>> def fn(x, y):
        return x * 10 + y
 
>>> reduce(fn, [1, 3, 5, 7, 9])
13579

Combined, we can write the int() function ourselves

from functools import reduce
 
a={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
 
def charnum(s):
    return a[s]
 
def strint(s):
    return reduce(lambda x, y: x * 10 + y, map(charnum, s))

Let’s continue to talk about some useful functions

22. split

Python  split()  slices the string by specifying the separator. If the parameter num has a specified value, only num substrings are separated.

grammar:

str.split(str="", num=string.count(str))

simplify:

str.split(“”)

23. combining theory with practice

1) Combined with the knowledge learned in the fourth period , we can write this line of code

print(” “.join(input().split(” “)[::-1]))

Realize the function, the original question of leetcode: Given a sentence (only containing letters and spaces), reverse the position of the words in the sentence, divide the words with spaces, and there is only one space between the words, and no spaces before and after. For example: (1) “hello xiao mi” -> “mi xiao hello”

2) Give another example:

Combine two integer arrays in ascending order and filter out duplicate array elements

Input parameters:

int* pArray1: integer array 1

intiArray1Num: the number of elements in the array 1

int* pArray2: integer array 2

intiArray2Num: the number of elements in the array 2

For python, it’s useless to give the number.

a,b,c,d=input(),list(map(int,input().split())),input(),list(map(int,input().split()))
print("".join(map(str,sorted(list(set(b+d))))))

3) We combine recent knowledge to make a problem:

Enter an int integer, and follow the reading order from right to left, and return a new integer without repeated numbers.

result=""
for i in input()[::-1]:
    if i not in result:
        result+=i
print(result)

There are a lot of specific and concise operations, so I won’t give examples here, let’s get more experience.

Okay, let’s continue with other functions.

24. filter

Python built-in filter()functions are used to filter sequences.

And map()similarly, filter()it also receives a function and a sequence. The map()difference is that filter()the passed function acts on each element in turn, and then decides Truewhether Falseto keep or discard the element according to the return value .

Simple example, delete even numbers:

def is_odd(n):
    return n % 2 == 1
 
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# result: [1, 5, 9, 15]

We can use the knowledge we have learned to realize the Ericht Sieve:

This code is not original:

#First construct an odd sequence starting from 3:
def _odd_iter():
     n = 1
     while True:
         n = n + 2
         yield n
#This is a generator and an infinite sequence.
 
#Filter function
def _not_divisible(n):
     return lambda x: x% n> 0
#Builder
def primes():
     yield 2
     it = _odd_iter() # initial sequence
     while True:
         n = next(it) # return the first number of the sequence
         yield n
         it = filter(_not_divisible(n), it) # construct a new sequence

Use filter()of new sequences that are continuously generated after screening

IteratorIt is a sequence of lazy calculation, so we can use Python to express the sequence of “all natural numbers” and “all prime numbers”, and the code is very concise.

25. sorted

>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
#You can receive a key function to implement custom sorting, such as sorting by absolute value:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

Let’s look at an example of string sorting:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']

By default, the sorting of strings is compared according to the size of ASCII, because ‘Z’ < ‘a’, as a result, uppercase letters Zwill be sorted before lowercase letters a.

Now, we propose that sorting should ignore case and sort in alphabetical order. To implement this algorithm, there is no need to make major changes to the existing code, as long as we can use a key function to map the string to ignoring case sorting. To compare two strings ignoring case is actually to first change the strings to uppercase (or all lowercase), and then compare them.

In this way, we sortedcan pass in the key function to achieve case-ignoring sorting:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

To perform reverse sorting, without changing the key function, you can pass in the third parameter reverse=True:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

As can be seen from the above examples, the abstraction capabilities of higher-order functions are very powerful, and the core code can be kept very concise.

sorted()It is also a higher-order function. With sorted()the key is to achieve a sorted mapping function.

Leave a Comment