Python leak detection tips (1)

cc_ mlearning 2021-11-25 08:44:19
python leak detection tips

Although with python It's been a long time , But I've never learned systematically , So knowledge is not systematic . In the process of writing code , Regardless of the cleanliness and simplicity of the code , Cause the program I wrote to run very slowly , It looks like it was written by vegetable chicken . So I decided to update it from time to time python Leak detection tips .

1. Use \ Line connector

 Insert picture description here
Common escape characters :\t( Horizontal tabs ) \n( Line break ).

2. object

The essence of the object is : A memory block , Have a specific value . Each object consists of id、type、value form .

  1. id Corresponds to the address of the object in computer memory , use id(obj) You can return objects obj Of id;
  2. type Represents the data type stored by the object , such as int、str、list etc. , Use type(obj) You can return the type of the object ;
  3. value Represents the data value stored by the object , Use print(obj) You can print out values .
     Insert picture description here

3. python Naming specification

 Insert picture description here

4. Series data assignment

  1. Assign null values to multiple variables at the same time list. The number of left and right sides must be consistent .
a, b = [], []
print(a)
>>> []
  1. Chained assignment , Either way .
a, b = 123, 123
a = b = 123
print(a)
>>> 123

5. Some common functions in string

5.1 split() and join()

I usually use split() More split strings , however join() Use less .

a = ['www', 'zhihu', 'com']
print('.'.join(a)) # Splice with dots , Can be replaced by other symbols .
>>> www.zhihu.com

It's a lot more convenient , I usually use string splicing , If you use string splicing in this example ( String addition ), Still in list Take each value from , It's much more troublesome .
 Insert picture description here
I feel like I still don't realize join() function , I still make mistakes when I use it myself , Just take chestnuts .

# For example, I want to form ' Jiujie immortal statue is finished.'
bookname = ' Jiujie immortal statue '
a = bookname.join('is finished.')
# print(a) # i Jiujie immortal statue s Jiujie immortal statue Jiujie immortal statue f Jiujie immortal statue i Jiujie immortal statue n Jiujie immortal statue i Jiujie immortal statue s Jiujie immortal statue h Jiujie immortal statue e Jiujie immortal statue d Jiujie immortal statue .
b = [bookname, 'is finished.']
c = ''.join(b) # You can use other symbols 
print(c) # Jiujie immortal statue is finished.

5.2 a.startswith() and a.endswith()

a = 'link.txt'
a.startswith('li') # >>> True
a.endswith('txt') # >>> True

e.g. There are many files in one folder , You can use this function to determine whether it is the file you want to read .

5.3 format()

print('name: {}, age: {}'.format('xiaoxi', 18))
>>> name: xiaoxi, age: 18

format() It's all preceded by strings , Fill in the blanks with {}.
Example :
 Insert picture description here

6. list

6.1 Inferentially create sequences

The derivation is typical python style .
 Insert picture description here

A command , But I often add commas, resulting in errors .
 Insert picture description here
The derivation of the dictionary :
 Insert picture description here

6.2 Common functions

There are many commonly used functions , such as len()、sorted()、max()、sum()、append() wait , Which one you need to use depends on the reference book .

6.2.1 How to list Add the element in to another list in .

Always used before append() function , But if I'm going to put one list Add the element in to another list in , Also use append() There will be problems .

list1=[1, 2, 3]
list2=['4', 6, 7]
#append()
# list1.append(list2)
# Print the current list1
# print(list1) # [1, 2, 3, ['4', 6, 7]]
list1.extend(list2)
print(list1) # [1, 2, 3, '4', 6, 7]

6.3 2 d list

Generally, one dimension is used more , A two-dimensional list is used to store table data .np.array() Form an array
 Insert picture description here

7. Tuples

Tuples I use very little , It's worth noting that :

  1. Create can use ()/tuple();
  2. Elements in tuples cannot be modified ;
  3. The access of elements in tuples is the same as that of lists .

7.1 zip()

Sometimes you want to merge multiple lists , But I don't want to put them in one list in , It can be used zip() function .
 Insert picture description here
Tuples can be used as dict Of key, but list no way , because dict in key Is the only immutable , but list It's a mutable object . The following example uses zip() Function formation dict Very convenient .
 Insert picture description here
zip() package .

name = ('xi', 'ming')
age = (18, 19)
jobs = ('student', 'coder')
# print(zip(name, age, jobs)) # result :<zip object at 0x000001BF04E61248>
# print(dict(zip(name, age, jobs))) # result : ValueError: dictionary update sequence element #0 has length 3; 2 is required
for name, age, jobs in zip(name, age, jobs):
print(name, age, jobs) # xi 18 student
break
# If instead list Well 
name = ['xi', 'ming']
age = [18, 19]
jobs = ['student', 'coder']
for name, age, jobs in zip(name, age, jobs):
print(name, age, jobs) # xi 18 student
break

8. Dictionaries

8.1 Dictionary reading

I usually get its corresponding value through the key , But the disadvantage of this method is that if the key you use does not exist, an error will be reported . While using dict.get() Is that , If the key does not exist , Returns the None, therefore , Recommended get() obtain dict Of “ value ”.

a = {
'name': 'xiaoxi', 'age': 18}
a.get('name')
>>> xiaoxi

8.2 Ergodic dictionary

a.items()、a.keys() / for key in dict: Traverse all key value 、a.values()
I often forget if there is s, Whether it's reading key value pairs 、 There are both keys and values .

8.3 update()

Put the new dictionary b Add all to the old dictionary a in , If key repeat , The new will cover the old .
 Insert picture description here

9. aggregate

Sets are unordered and mutable 、 Data structure with non duplicate elements .
For creation {}/set()、 Add elements with add()、 Based on the feature that elements do not repeat , You can redo the list .
Sets are characterized by disorder , Traversal method and list equally , Use both for loop .

10. Control statement

if-else/ if-elif-else Judgment statement 、for、while And so on .

10.1 matters needing attention

  1. while Cycle starts when condition is true ;
  2. break and continue.

break Statement for while and for loop , To end the cycle . When there are nested loops ,break Statement can only jump out of the nearest loop .

continue Statement is used to end the loop , Go on for the next time . When multiple loops are nested ,continue It is also applied to the nearest layer of loop .

10.2 Loop code optimization

  1. Minimize unnecessary calculations inside the loop ;
  2. Nested loop , Calculation of inner circulation of gold reduction , Lift out as much as possible ;
  3. Local variable query is faster , Try to use local variables ;
  4. Concatenate multiple strings , use join() without ’+‘.
版权声明
本文为[cc_ mlearning]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/11/20211109004844339J.html

  1. Python common operators
  2. Python data type
  3. get和post接口的封装(python)
  4. Python variables and memory
  5. Encapsulation des interfaces get et post (Python)
  6. Écrivez un programme Python pour convertir les décimales en décimales binaires. Notez que le paramètre longueur est utilisé pour spécifier le nombre de bits convertis
  7. Switching Python version through terminal under MacOS
  8. Créer un tableau de visualisation des données de vente en python pour démontrer que l'analyse est en place
  9. Python crawling chain home network listing information
  10. Pandas learning experience
  11. Visualisation des données Python: visualisation du plug - in D - Tale pour l'analyse des données
  12. [test and development practice] Alfred + Python + Charles quickly debug the HTTP interface
  13. [tiktok] adb+python automatically brush fast / Kwai and video to earn gold coins.
  14. [efficiency tool] Based on Python crawler's "NBA match information and data statistics view" Alfred gadget
  15. [efficiency tool] the MAC side's JSON string re parsing tool based on Alfred and python perfectly parses JSON strings
  16. Hello python world
  17. Exception handling mechanism for getting started with Python
  18. Advanced Python: outer functions, inner functions, and closures
  19. The difference between single quotation marks, double quotation marks, three single quotation marks and three double quotation marks in Python
  20. Python operation database class: realize the functions of creating tables, inserting data and querying data
  21. Introduction to Python 3 crawler and regular expression
  22. Python exercise (11.7)
  23. python11~20
  24. Matlab, python example exercise -- Day2
  25. Matlab, python example exercise -- Day1
  26. White Python road -- Day5
  27. Python正则表达式选择字符
  28. The white way of Python -- day4 (I can't learn it gradually)
  29. The white way of Python -- Day3
  30. The white Python road -- Day2
  31. The white way of Python -- Day1
  32. Difference between input in python2 and python3
  33. Exception handling in Python
  34. Metaclass and singleton pattern of Python
  35. Python methods and functions
  36. Python regular expression select Characters
  37. Introduction to Python object-oriented reflection and built-in methods
  38. Object oriented composition of Python
  39. Python object oriented polymorphism
  40. Object oriented encapsulation of Python
  41. Object oriented inheritance in Python
  42. Python Software Development Directory
  43. Python package
  44. Python module
  45. Python is process oriented and functional
  46. Python function recursion
  47. Python generator
  48. Python iterator
  49. Python decorator
  50. Python function closure
  51. Python namespace and scope
  52. Python function
  53. Python file processing
  54. Python data type
  55. Process control of Python
  56. Garbage collection mechanism of Python
  57. Python: the field notes of dtype = 'object' can also be arranged in ascending and descending order
  58. . value in pandas_ Usage of counts()
  59. 202111 | some hands-on practice of Python time function
  60. 202111 | in Python, timestamp, time string and real date time are converted to each other