程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python question brushing] - Summary of practical skills (continuous update...)

編輯:Python

List of articles

List of articles

  • List of articles
  • Preface
  • One 、python Practical skills
    • 1. Calculate character difference
    • 2. String inversion
    • 3. Array element count
    • 4. Dictionary traversal
    • 5. Initialize all 0 Array
    • 6. Counter Count
    • 7. bisect Usage of
    • 8. List to heavy
    • 9. Convert list to string
    • 10. map function
    • 11. collections.deque
    • 12. Priority Queue
    • 13. A two-dimensional list Sort by the value of a column
    • 14. f-string Usage of
    • 15. zip Function usage
    • 16. utilize get() Method to get the dictionary value
    • 17. collections.OrderedDict Orderly dictionary
    • 18. Take the largest dictionary value Value correspondence key
    • 19. @lru_cache Decorator usage
    • 20. The order of dictionaries
    • 21. Determine whether the string consists of all letters
    • 22. For an iteratable object ( Dictionaries , list , Tuples , etc. ) Multi step sorting
    • 23. The list cannot be used as a key to the dictionary , But tuples can
    • 24. Exchange two numbers in place
    • 25. Chain comparison operators
    • 26. Store list elements in new variables
    • 27. Print the file path of the incoming module
    • 28. Interactive environment “—” The operator
    • 29. How to use input Enter multiple data
    • 30. Get both index and subscript
    • 31. Memory address query
    • 32. Convert two lists to dictionaries
    • 33. List element frequency statistics ( Use a dictionary )
    • 34. Object memory usage query
    • 35. Check for duplicate elements
    • 36. Find the most frequent occurrences in the list
    • 37. Reverse list
    • 38. Two ways to merge lists
    • 39. Dictionary derivation (Dictionary comprehensions) And set derivation (Set comprehensions)
    • 40. since python3.1 rise , We can use the same syntax to create sets and dictionary tables
    • 41. Iteration tools
    • 42. Debug script
    • 43. How to use input Enter multiple data
  • summary


Preface

One 、python Practical skills

1. Calculate character difference

python Character subtraction is not allowed , When subtraction between characters is required , We can use ord() function ,ord() The function is python Self contained function , No need to import .

print(ord('b')-ord('a'))
#result:1

2. String inversion

string = 'leetcode'
print(string[::-1])
#result:edocteel

3. Array element count

import collections
li = [1,2,2,4,5,5]
cnt = collections.Counter(li)
print(cnt)
#result:Counter({
2: 2, 5: 2, 1: 1, 4: 1})

4. Dictionary traversal

cnt = {
1:4,2:3}
# Traversal key value pairs
for item in cnt.items():
print(item)
# Traversal keys
for item in cnt.keys():
print(item)
# Traversal value
for item in cnt.values():
print(item)

result:

(1, 4)
(2, 3)
1
2
4
3

5. Initialize all 0 Array

li = [0]*length # The first one is
li = [0 for i in range(length)] # The second kind
li = [[0]*3 for i in range(4)] # Two dimensional array

6. Counter Count

from collections import Counter
colors = ['red','blue','red','green','blue','blue']
c = Counter(colors)
print(c)
print(dict(c))

result:

Counter({
'blue': 3, 'red': 2, 'green': 1})
{
'red': 2, 'blue': 3, 'green': 1}

7. bisect Usage of

bisect yes python The built-in modules , For insertion and lookup of ordered sequences
lookup :bisect(array,item)
Insert :bisect(array,item)

import bisect
a = [1,2,2,5,8]
position = bisect.bisect(a,7)
print(position)
#4
bisect.insort(a,4) # Find the location to insert
print(a)
#[1,2,2,4,5,8]
bisect.bisect_left(a,2) # Insert to left
#1
bisect.bisect_right(a,2) # Insert to the right
#3

8. List to heavy

l1 = [1,4,4,2,3,4,5,6,1]
l2 = list(set(l1))
print(l2)
#result:[1, 2, 3, 4, 5, 6]

9. Convert list to string

li = ['a','b','c']
print(' '.join(str(i) for i in li))

10. map function

def square(x):
return x**2
a = list(map(square,[1,2,3,4,5])) # Calculate the square of each element of the list
b = list(map(lambda x:x**2,[1,2,3,4,5,])) # use lambda Anonymous functions
print(a,b)
#result:[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]

11. collections.deque

deque It's a two terminal queue (double-ended queue) Abbreviation , Because both ends can be edited ,deque It can realize stack (stack), Queues can also be implemented (queue)

from collections import deque
# que = collections.deque()
a=deque([1,2,3])
a.pop()
# [1,2]
a.append(4)
# [1,2,4]
a.popleft()
# [2,4]
a.appendleft(0)
# [0,2,4]

comparison list Implemented queue ,deque The implementation has lower time and space complexity .list Get out of the team (pop) And insert (insert) The space of time
The complexity is about O(n),deque Out of the team (pop) And join the team (append) The time complexity is O(1).

12. Priority Queue

from queue import PriorityQueue
Q = PriorityQueue()
Q.put(3)
Q.put(2)
Q.put(1)
Q.get()

Priority queue , The default is sorted from small to large

13. A two-dimensional list Sort by the value of a column

li = [[1,3],[8,10],[2,6],[15,18]]
li.sort(key=lambda x:x[0])
li
print(li)
#result:[[1, 3], [2, 6], [8, 10], [15, 18]]

14. f-string Usage of

name = 'python'
f'Hello {name}'
print(f'Hello {name}')

15. zip Function usage

systems = ['windows','ubuntu','mac']
version = ['20.20','19.10','21.20']
countries = ['UK','Chinese','US']
for system,ver,country in zip(systems,version,countries):
print(f'{
system} plays in {
ver}.country:{
country}')

16. utilize get() Method to get the dictionary value

person = {
'name':'YQ','age':22}
print('Name:',person.get('name'))
print('Age:',person.get('age'))
print('Salary:',person.get('salary'))

result:

Name: YQ
Age: 22
Salary: None

17. collections.OrderedDict Orderly dictionary

from collections import OrderedDict
mydict = OrderedDict({
'a':2,'b':1,'c':0})
for key,value in mydict.items():
print(key,value)

result:

a 2
b 1
c 0

18. Take the largest dictionary value Value correspondence key

nums = [1,2,2,2,3,4,4]
from collections import Counter
cnt = Counter(nums)
print(max(cnt.keys(),key = cnt.get))
#result:2

19. @lru_cache Decorator usage

NameError: name 'lru_cache' is not defined
from functools import lru_cache

A decorator that provides caching for functions , Directly used in a user-defined function , The next time you call with the same parameter, you will directly return the last result
lru_cache maxsize The default value of the parameter is 128. If it is set to None, The cache can grow indefinitely

from functools import lru_cache
@lru_cache(maxsize = None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)

20. The order of dictionaries

# Dictionary sort
a = {
'a':3,'c':89,'b':0,'d':34}
# Sort by dictionary value
a1 = sorted(a.items(),key = lambda x: x[1])
# Sort by dictionary key
a2 = sorted(a.items(),key = lambda x: x[0])
print(' Results sorted by value ',a1)
print(' Press the key to sort the results ',a2)
print(' The result is converted to dictionary format ',dict(a1))
print(' The result is converted to dictionary format ',dict(a2))

result:

 Results sorted by value [('b', 0), ('a', 3), ('d', 34), ('c', 89)]
Press the key to sort the results [('a', 3), ('b', 0), ('c', 89), ('d', 34)]
The result is converted to dictionary format {
'b': 0, 'a': 3, 'd': 34, 'c': 89}
The result is converted to dictionary format {
'a': 3, 'b': 0, 'c': 89, 'd': 34}

21. Determine whether the string consists of all letters

my_str = 'python'
my_str.isalpha()
print(my_str.isalpha())

22. For an iteratable object ( Dictionaries , list , Tuples , etc. ) Multi step sorting

Multi step sorting , for example : Sort by content first , If the content is the same, then follow ID Sort

my_test = ["b:7","a:7","c:4","d:3"]
def f(log):
id_,rest = log.split(":",1)
return (rest,id_)
print(sorted(my_test,key=f))
#result:['d:3', 'c:4', 'a:7', 'b:7']

Take the example above , First sort by string value , Then according to the string id Sort

23. The list cannot be used as a key to the dictionary , But tuples can

Sometimes you need to use a dictionary to count the number of the same elements in a list , But maybe an element is also a list , You can't use it directly at this time
collections.Counter To statistics , You need to convert the elements of the original list to tuple

1、 Array operation

1.1. Traversal array , Enumerate indexes and values

for i,j in enumerate([1,2,34,5,56,4]):
#i Index 
#j Value 

1.2. An array of reverse

a = [1,2,3,4,5]
a[::-1]
a.reverse()

1.3. Array sorting

a = [1,2,6,8,0,3,4]
a.sort()
a = [[1,3],[2,4],[5,0]]
sort(key = lambda x:x[0]) # According to the first number is key Sort

1.4. Array merge

a = [1,2,6,8,0,3,4]
b = [2,5,9]
a.extend(b)
a.[len(a):]=b

1.5. Build stacks and queues

a = [1,2,6,8,0,3,4]
a.append() # Add... At the end of the array
a.insert(x,3) # The index is x Insert at 3
a.pop() # Delete the tail element
a.pop(0) # Delete index as 0 The elements of
a = [] # Build stack
a.append()
a.pop()
a = []
a.append()
a.pop(0)

1.6. Array weight removal

# Turn into set, Convert to list
a = [1,1,1,3,4,4]
a = list(set(a))

1.7. Find array

a.index(3)

2、 String manipulation

2.1. Remove the space

a = ' hello world '
a.strip() # Remove all spaces on both sides
a.lstrip() # Remove the space on the left
a.rstrip() # Remove the space on the right

2.2. Replace character

# take a Medium x Replace with yyy, You can put spaces ' ' Replace with '' Equal to removing spaces
a.replace('x','yyy')

2.3. Merge characters

a = 'hello'
b = 'world'
c = a + b

2.4. Judge the composition of characters

# If string Only Numbers are returned true, Otherwise return to False
a.isdigit()
# If string Returns at least one character and all characters are letters or Numbers True, Otherwise return to False
a.isalnum()
# If string Returns at least one character and all characters are letters True, Otherwise return to False
a.isalpha()

2.5. Convert array to characters

# With string As a separator , take seq All the elements in ( String representation of ) Merge into a new string
#string.join(seq)
a = [1,2,3,4]
#''.join(a) # The result is '1234'
print(' '.join('%s' %id for id in a))

24. Exchange two numbers in place

python Provides an intuitive way to assign and exchange values in a single line of code ( A variable's value ) Methods

x,y = 10,20
print(x,y)
x,y = y,x
print(x,y)

The right side of the assignment forms a new tuple , Parse now on the left (unpack) that ( Not quoted ) Tuples to variables and , Once the assignment is complete , The new tuple becomes unreferenced and marked for garbage collection , Finally, the exchange of variables is completed

25. Chain comparison operators

Aggregation of comparison operators is another sometimes convenient technique :

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

26. Store list elements in new variables

We can use lists to initialize multiple variables , When parsing the list , The number of variables should not exceed the number of elements in the list :[ The number of elements and the length of the list should be exactly the same ]

testList =[1,2,3]
x,y,z = testList
print(x,y,z) #1 2 3

27. Print the file path of the incoming module

If you want to know the absolute path to the module referenced in the code, you can use

import threading
import socket
print(threading)
print(socket)

28. Interactive environment “—” The operator

This is a useful feature that most of us don't know , stay python Console , Whenever we test an expression or call a method , The result is a temporary variable :_

29. How to use input Enter multiple data

# Method 1 :
#List = eval(input(' Enter several numbers , Separate with commas :'))
# Method 2 :
#List = List(map(int,input(' Input number , Space off ').split()))
#int It can be replaced by float etc. , The resulting data is of the corresponding type 
# explain :
#1. map()
#map() The function takes two arguments , One is a function , One is the sequence ,map Apply the incoming function to each element of the sequence in turn , And take the result as a new list return 
#2. split()
# Split string , Slice a string by specifying a separator , And return the separated string list
#3. map(function,input(" Separate... By spaces ").split())
# because input() The output is a string separated by spaces ,split() The values are separated and placed in the list , At this point, the value in the list is string , If you want to calculate , Then it must be in map() In the use of int() or float() And then assign values after processing

30. Get both index and subscript

List = [1,2,3,4,5,6]
for i,j in enumerate(List): #i Subscript ,j For the corresponding data
print("data:",end=' ')
print("index",i)

result:

data: index 0
data: index 1
data: index 2
data: index 3
data: index 4
data: index 5

31. Memory address query

a = 123
b = 'blue'
print(id(a)) # Different computers , Values should be different
print(id(b))

32. Convert two lists to dictionaries

a = ['A','B','C','D','E']
b = [1,2,3,4,5]
# Method 1 :
c1 = dict(zip(a,b))
# Method 2
c2 = {
key:value for key,value in zip(a,b)}
# Method 3
c3 = {
} # Initialize an empty dictionary
for k,v in zip(a,b):
if k not in c3.keys(): # Judge k Whether in c3 In the dictionary key
c3[k] = v
print(c1)
print(c2)
print(c3)

result:

{
'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
{
'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
{
'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

33. List element frequency statistics ( Use a dictionary )

a = [1,2,3,1,2,4,6,5,6,6,7,9,10,10]
b = {
}
for i in a:
if i not in b.keys():
b[i] = 1
else:
b[i] =b[i] + 1
print(b)
#result:{
1: 2, 2: 2, 3: 1, 4: 1, 6: 3, 5: 1, 7: 1, 9: 1, 10: 2}

34. Object memory usage query

from sys import getsizeof
a = 100
b = 'green'
print(getsizeof(a)) #28
print(getsizeof(b)) #54

35. Check for duplicate elements

List1 = [1,2,3,4,56]
List2 = [1,1,3,4,5,5]
print(" There are repeating elements :",len(List1) != len(set(List1))) # There are repeating elements :False
print(" There are repeating elements :",len(List2) != len(set(List2))) # There are repeating elements :True

explain :set(x) Function can be used for collection generation , The parameters can be any data type , The returned result is a set with no repetition and arbitrary sorting ,
in other words , If the input data is duplicated , The returned result will also make the duplicate data non duplicate

36. Find the most frequent occurrences in the list

# Method 1 :
List1 = [1,2,3,4,56,11,2,3,4,5,6,7,1,2,3,1,1,1,19]
print(max(set(List1),key = List1.count)) #1
# Method 2 :
from collections import Counter #python Built in libraries for
ct = Counter(List1)
print(ct.most_common(1)) # The one with the highest output frequency #[(1,5)] 1 appear 5 Time

37. Reverse list

List1 = [1,2,5,4,7,6]
List2 = List1[::-1]
print(List2) #[6, 7, 4, 5, 2, 1]

38. Two ways to merge lists

list1=[1,2,5,4,7,6]
list2=['A','B','C','D']
list3=list1+list2# Direct addition
list4=list1.extend(list2)# Of the call list extend Method
print(list3) #[1, 2, 5, 4, 7, 6, 'A', 'B', 'C', 'D']
print(list4) #None
print(list1) #[1, 2, 5, 4, 7, 6, 'A', 'B', 'C', 'D']

explain : Why? list4 by None? Actually , This is very important , List append and extend Method will modify the original list , Will not return a new list , The return value is None.

39. Dictionary derivation (Dictionary comprehensions) And set derivation (Set comprehensions)

Most of the python Programmers know and use list derivation list comprehensions, If you are right about list comprehensions Not familiar with , Shorter :

some_list = [1,2,3,4,5]
another_list = [x + 1 for x in some_list]
print(another_list) #[2, 3, 4, 5, 6]

40. since python3.1 rise , We can use the same syntax to create sets and dictionary tables

some_list = [1,2,3,4,5,2,5,1,4,8]
even_set = {
x for x in some_list if x %2 == 0}
print(even_set) #{
8, 2, 4}
set([8,2,4])
d = {
x: x%2 == 0 for x in range(1,11)}
print(d) #{
1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

In the first example , We use some_list Based on , Create a collection with non repeating elements , And the set contains only even numbers , And in the dictionary table , We created
One key Is not repeated 1 To 10 Integer between ,value It's Boolean , Used to indicate key Is it an even number
Another important thing to note here is the literal representation of sets , We can simply create a collection in this way

my_set = {
1,2,1,2,3,4}
print(my_set) #{
1, 2, 3, 4}

41. Iteration tools

and collections Like the library , There is also a library that is more itertools, It can effectively solve some problems , One of the use cases is to find all the combinations

from itertools import combinations
teams = ["Packers","49ers","Ravens","Patriots"]
for game in combinations(teams,2):
print(game)

result:

('Packers', '49ers')
('Packers', 'Ravens')
('Packers', 'Patriots')
('49ers', 'Ravens')
('49ers', 'Patriots')
('Ravens', 'Patriots')

42. Debug script

With the help of the module, we can python Set breakpoints in the script

import pdb
pdb.set_trace()

43. How to use input Enter multiple data

# Method 1 :
#List = eval(input(' Enter several numbers , Separated by commas :')) # Enter any number , All saved to list in 
# Method 2 :
#List = list(map(int(input(' Input number , Space off ').split())))
#int Can be replaced by float etc. , The resulting data is of the corresponding type 
# explain :
1.map()
map Function takes two parameters , One is a function , One is the sequence ,map Apply the incoming function to each element of the sequence in turn , And take the result as a new list return
2.split()
split Split string , Slice a string by specifying a separator , And returns a list of split strings
3.map(function,input(" Separate... By spaces ").split())
because input() The output is a string separated by spaces ,split() The values are split and placed in the list , At this point, the value in the list is string \
If you want to use it in an operation , Then it must be in map() In the use of int() or float() Wait for the treatment , To assign a value

summary

Share :
Experience is a potential condition for our innovation . Strictly speaking , Experience without experience , Experience is a condition for innovation , otherwise , Experience will become an obstacle to innovation . There are different levels of experience . To sublimate wisdom , We should learn from high-level experience as much as possible —
This not only provides us with a way forward , It also provides ideas for selection , Make it the starting point for triggering new success .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved