Python knowledge points notes


Record some knowledge points encountered on python to facilitate future query.

1. lambda

Lambda is essentially a function written in one line. The left side of the colon is the function input value, and the right side is the return value. There can be multiple inputs and returns.

lambda x:x+1

lambda x, y:x+y

2. map()

map() will map the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence, which is equivalent to performing a function operation on each element in the iterable object that is input subsequently.
Return a map iterator, which can be converted to list and set objects for viewing using list() or set().
map(function, iterable, …)

list(map(lambda x:x+1, [1, 2, 3]))

list(map(lambda x, y:x+y, [1, 2, 3], [4, 5, 6]))

3. Python uses map to operate in parallel

A tutorial on how to use multi-threaded maps.
https://www.cnblogs.com/wangxusummer/p/4835929.html
https://www.cnblogs.com/sthu/p/9355759.html

4. Use * to unpack and use zip() to pack

When the input is a list of undetermined length, and the function input requires all variables to be input separately, use * to expand each element in the list separately as a variable input.
Some functions of the numpy library sometimes need to be input in this way.

The zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list of these tuples.
If the number of elements in each iterator is inconsistent, the length of the returned list is the same as the shortest object.

# 使用python一行完成矩阵旋转
# 转自https://leetcode-cn.com/problems/rotate-image/comments/712701

nums = [[1,2,3],[4,5,6],[7,8,9]]
# 使用*反序解包
print(*nums[::-1])
# [7, 8, 9] [4, 5, 6] [1, 2, 3]

# 使用zip将元素挨个打包
nums[:] = zip(*nums[::-1])
print(nums)
# [(7, 4, 1), (8, 5, 2), (9, 6, 3)]

5. reduce() function

The elements in the parameter sequence will be accumulated.

The function performs the following operations on all the data in a data set (linked list, tuple, etc.): Use the function function (with two parameters) passed to reduce to operate on the first and second elements in the set, and get The result is calculated with the third data using the function function, and finally a result is obtained.
Example: To sum each number in the list

from functools import reduce

def get_sum(nums):
    return reduce(lambda x, y: x + y, nums)		
	
print(get_sum([1,3,5,6]))

6. Bitwise operators

& Bitwise AND operator
| bitwise OR operator
^ bitwise XOR operator: when the two corresponding binary bits are different, the result is 1
~ bitwise negation operator
<< Left shift operator: of the operand All binary bits are shifted to the left by several bits. The number on the right of << specifies the number of bits to move. The high bits are discarded, and the low bits are filled with 0.
Same as: >> Right shift operator: shift all the binary bits of the operand on the left of ">>" by a few digits, and the number on the right of >> specifies the number of digits to move

Example: Given a non-empty integer array, except for a certain element that appears only once, every other element appears twice. Find the element that appears only once. Use the exclusive OR operation to get the result.

def singleNumber(nums):
	return reduce(lambda x, y: x ^ y, nums)

7. Use [:] to change the value of the list itself without the function returning

def merge(a, b):
		a = a + b
		
a = [1, 2, 3]
b = [4, 5, 6]

merge(a, b)
print(a)

[1, 2, 3]

def merge(a, b):
		a[:] = a + b
		
a = [1, 2, 3]
b = [4, 5, 6]

merge(a, b)
print(a)

[1, 2, 3, 4, 5, 6]

8. Query the index of the first specified element in the list

# 查询第一个指定元素的位置
index = list_1.index(element)

9. Regular Expressions

Identify the number at the beginning of the string, the code and description are transferred from leetcode

def myAtoi(self, s):
        return int(*re.findall('^[\+\-]?\d+', s.lstrip()))

作者:QQqun902025048
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/python-1xing-zheng-ze-biao-da-shi-by-knifezhu/
来源:力扣(LeetCode)

^:匹配字符串开头
[\+\-]:代表一个+字符或-字符
?:前面一个字符可有可无
\d:一个数字
+:前面一个字符的一个或多个
\D:一个非数字字符
*:前面一个字符的0个或多个

10. enumerate() function

The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, and list data and data subscripts at the same time.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

11. Heap

# 导入库
from heapq import * 

# 用一个列表充当堆
heap = [] 

# 加入元素
for i in range(10):
	heappush(heap, i)
	
# 取出最小元素
min_val = heappop(heap)

# 将普通列表整理为一个最小堆
list1 = [4, 3, 1, 2, 7]
heapify(list1)
# list1 = [1, 2, 4, 3, 7]

# 将所有数字取负输入,再取负输出,即可将其作为最大堆使用。
list2 = list(map(lambda x:-x,[4, 3, 1, 2, 7]))
heapify(list2)
# list2 = [-7, -4, -1, -2, -3]

# 也可以按照元素的顺序进行对第一个元素的排序
list3 = [(4,1), (3,9), (1,4), (2,3), (7,2)]
heapify(list3)
print(list3)
# list3 = [(1, 4), (2, 3), (4, 1), (3, 9), (7, 2)]

12. Use sorted() and reversed() to sort or reverse the list locally

a = [4, 3, 1, 2, 0]

a[:4] = reversed(a[:4]) 
print(a)
# [2, 1, 3, 4, 0]

a[:4] = sorted(a[:4]) 
print(a)
# [1, 2, 3, 4, 0]

13. filter()

The filter() function is used to filter the sequence, filter out the elements that do not meet the conditions, and return a new list of elements that meet the conditions.

It should receive two parameters, the first is a function, and the second is a sequence. Each element of the sequence is passed as a parameter to the function for judgment, and then returns True or False, and finally the element that returns True is placed in the new list.

def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

[1, 3, 5, 7, 9]

14. Permutation and Combination

itertools.permutations() lists the permutation possibilities.
itertools.combinations() lists the combination possibilities.

import itertools

list1 = [1, 2, 3]

# 包含3个值的情况下所有的排列可能性
list2 = list(itertools.permutations(list1,3))
print(list2)
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

# # 包含3个值的情况下所有的组合可能性
list3 = list(itertools.combinations(list1,2))
print(list3)
# [(1, 2), (1, 3), (2, 3)]

15. Factorial factorial()

import math
num = math.factorial(6)
print(num)

16. repr() handles escape characters

When you need to input the path from cmd or file, for example, the path "E:\V1R2\product\fpgadrive.c", and then you need to cut out the last file name, you may encounter /f being judged as a single character, which may not be correct Identify the position of the last /.
For the string in the code, you can simply add r to the front of the code to solve it, but for the read string, you can only use the variable name to operate it.
At this point, you can use repr(input) to get the original string input and then search for // to get the file name.
Note: repr(input) will cause the beginning and last characters of the string to become', which can be removed by [1:-1].

a = repr(input())
# 输入E:\V1R2\product\fpgadrive.c
print(a)
# 'E:\\V1R2\\product\\fpgadrive.c'
a = a[1:-1]
print(a)
# E:\\V1R2\\product\\fpgadrive.c
for i in range(len(a)-1,-1,-1):
	if a[i] == "\\":
		print(a[i+1:])
		# fpgadrive.c
		break

17. CMD input abort judgment for unknown input lines

Based on exception capture

while True:
    try:
        deal_with(input())
    except:
        break


Note based on sys : This method will cause a line break of \n at the end of the read line, which may cause additional line break errors in the output of some questions.

import sys
while True:
    line = sys.stdin.readline()
    if not line:
        break
    deal_with(line)

18. High-order matrix deep copy

In the case of not using Numpy, you can use [:] to make a deep copy of the original python list, but if the list is a second-order matrix or above, the effect of the deep copy on the internal elements is still only a shallow copy. At this time, you can Solved by calling the copy library.

import copy
a = [[1,2],[3,4]]
b = copy.deepcopy(a)

19. String case conversion

s.upper() #把所有字符中的小写字母转换成大写字母
s.lower() #把所有字符中的大写字母转换成小写字母
s.capitalize() #把第一个字母转化为大写字母,其余小写
s.title() #把每个单词的第一个字母转化为大写,其余小写 

20. Random number generation

# 生成 0 ~ 2 之间的随机数
import random
 
print(random.randint(0,2))

21. Base conversion

Convert decimal to other bases
Binary: bin()
Octal: oct()
Hexadecimal: hex()

22. Count the number of occurrences of each element

from collections import Counter
string = "asfhaisfhaoif"
res = Counter(string)
print(res)
# Counter({'a': 3, 'f': 3, 's': 2, 'h': 2, 'i': 2, 'o': 1})

23. Use bit arithmetic to determine odd and even numbers

'''
判断奇偶  (二进制数以1结尾是奇数,以0结尾是偶数)

奇数&1==1

偶数&1==0
'''
print(6&1)
# 0
print(9&1)
# 1

24. Store objects on disk

Use pickle to save any python object on disk for the next call.

pickle.dump(obj, file[, protocol])
  serializes the object and writes the resulting data stream to the file object. The parameter protocol is the serialization mode, and the default value is 0, which means serialization in the form of text. The value of protocol can also be 1 or 2, which means serialization in binary form.

pickle.load(file)
  deserialize the object. Parse the data in the file into a Python object.

import pickle  

a = ["fafa",(24,55)]
# 写入二进制文件
with open("pickle_test.pkl","wb") as f:
	pickle.dump(a,f,1)
	
# 读出二进制文件
with open("pickle_test.pkl","rb") as f:
	b=pickle.load(f)

print(b)
# ['fafa', (24, 55)]

25. Sort by dictionary value

Original link: https://blog.csdn.net/u013193903/article/details/81096367

# 现在想对字典进行排序,根据value的第一个值,即列表的第一个数字
test_dict = {
    
    
    'a': [1, 'n'],
    'b': [2, 'k', 'b'],
    'c': [5, 'h1', 'h2', 'h3', 'h4', 'h5'],
    'd': [3, 'dfg1', 'dfg2', 'df3'],
    'e': [4, 'dfg1', 'dfg2', 'dfg3', 'dfg4'],
    'f': [2, 'dfgl', 'dfg2'],
    'g': [2, 'f1', 'f2'],
}

tmp = sorted(test_dict.items(), reverse=True, key=lambda x: x[1][0])

# >>> test_dict.items()
# dict_items([('a', [1, 'n']), ('b', [2, 'k']), ('c', [5, 'h']), ('d', [10, 'dfg']), ('e', [4, 'dfg']), ('f', [2, 'dfgl']), ('g', [2, 'f'])])
# 这里的test_dict.items()实际上是将test_dict转换为可迭代对象
# ('a', [1, 'n']), ('b', [2, 'k']), ('c', [5, 'h']), ('d', [10, 'dfg']), ('e', [4, 'dfg']), ('f', [2, 'dfgl']), ('g', [2, 'f'])

# 用的是元组的第二值,即列表,取列表的第一个值,就是需要排列的数字,key=lambda x: x[1][0]

26. ASCII code and character conversion

# 用户输入字符
c = input("请输入一个字符: ")
 
# 用户输入ASCII码,并将输入的数字转为整型
a = int(input("请输入一个ASCII码: "))
 
 
print( c + " 的ASCII 码为", ord(c))
print( a , " 对应的字符为", chr(a))

Guess you like

Origin blog.csdn.net/starvapour/article/details/112432180