25 must-know Python programming 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)

 

Many people learn python and don't know where to start.

Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.

Many people who have done case studies do not know how to learn more advanced knowledge.

So for these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and the source code of the course! ??¤

QQ group: 701698587

Principle: The right side of the assignment forms a new tuple, and the left side immediately unpacks that (unquoted) tuple to the variables <a> and <b>. 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.

Second, the chain-like comparison operator
Python does not require many conditions to write one by one, the comparison operator can aggregate.

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


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 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


 In the list comprehension:

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


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)


In the class:

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


 

4. Multi-line string
This is much more convenient than c. It is really uncomfortable to put a newline character in c and escape.

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


Five, in judgment
can be directly used to judge 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:

Six, four ways to flip strings/lists
 

# 翻转列表本身

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


# 在一个循环中翻转并迭代输出

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


# 一行代码翻转字符串

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


# 使用切片翻转列表

[1, 3, 5][::-1]
 
 
 
#输出 [5,3,1]。


 

Seven, initialize multiple variables at once
 

 Can be assigned directly:

a,b,c,d=1,2,3,4
can use the list:

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


(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'>


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

#列表
l=[[0 for i in range(4)] for i in range(4)]#生成二维列表
print(l)
#  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
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}


Ten, 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))
#以join左边的字符做分割


Eleven, 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


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

Thirteen, open file sharing
Python allows to run an HTTP server to share files from the root path, the following is the command to open the server:

python3 -m http.server

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. Debugging scripts
We can set breakpoints in Python scripts with the help of the <pdb> module, for example:

import pdb
pdb.set_trace()


Fifteen Directly iterating sequence elements
For sequences (str, list, tuple, etc.), directly iterating sequence elements is faster than iterating element index.

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


16. Clever use of the else statement (important)
Python's else clause can be used not only in if statements, but also in for, while, and try statements. 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)


while and for are similar

Take a look at try:

try:
    a()
except OSError:
    #语句1
else:
    #语句2


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

Summarize the else: f

or:

  仅当 for 循环运行完毕时(即 for 循环没有被 break 语句中止)才运行 else 块。

while:

  仅当 while 循环因为条件为假值而退出时(即 while 循环没有被break 语句中止)才运行 else 块。

try:

  仅当 try 块中没有异常抛出时才运行 else 块。

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.

 

 The normal understanding 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."

 

Seventeen, the usage and role of
except try/except: Catch the exception caused by PYTHON itself or in the process of writing the program and restore it

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
is also a 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().

 

Nineteen, python container
list: variable elements (any data type), ordered (indexable), append/insert/pop;

Tuples: The elements are immutable, but the variable elements in the elements are variable; ordered (indexable); and tuples 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

 

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

For example, if we have a function f(x)=x2, if we want to apply this function to a list [1, 2, 3, 4, 5, 6, 7, 8, 9], we can use map() The implementation is 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]


As a higher-order function, map() actually abstracts the rules of operation. Therefore, we can not only calculate simple f(x)=x2, but also calculate arbitrarily complex functions, such as converting all numbers in this list into characters string:

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


 

21. Reduce
reduce applies a function to a sequence [x1, x2, x3, ...]. This function must receive two parameters. Reduce continues 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

Twenty-two. 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("")

Twenty-three, 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.

 

Twenty-four. filter The
built-in filter() function of Python is used to filter sequences.

Similar to map(), filter() also receives a function and a sequence. Unlike map(), filter() applies the passed function to each element in turn, and then decides whether to keep or discard the element according to whether the return value is True or False.

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]))
# 结果: [1, 5, 9, 15]


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

Related knowledge of Ehrlich Sieve: https://blog.csdn.net/hebtu666/article/details/81486370

This code is not original:

#先构造一个从3开始的奇数序列:
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
#这是一个生成器,并且是一个无限序列。
 
#筛选函数
def _not_divisible(n):
    return lambda x: x % n > 0
#生成器
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) # 构造新序列


Use filter() to continuously generate new sequences after screening

Iterator is a sequence of lazy calculations, so we can use Python to represent sequences such as "all natural numbers" and "all prime numbers", and the code is very concise.

 

Twenty-five, sorted
 

>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
#可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序:
>>> 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. As'Z' <'a', as a result, the uppercase letter Z will be sorted before the lowercase letter 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 can pass the key function to sorted to achieve case-insensitive 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() is also a higher-order function. The key to sorting with sorted() is to implement a mapping function.

Guess you like

Origin blog.csdn.net/Python_kele/article/details/115014617