Catalog :

int Integers

bool Boolean

str character string

list list

tuple Yuan Zu

dict Dictionaries

set aggregate

Conversion between data types

Deletion of lists and dictionaries

Orderly dictionary

enumeration

Depth copy

Sort by hash

A non hashable data type can be changed into a data type :list、dict、set

Hashable data types are immutable data types :int、str、tuple、bool

python By means of type( object ) Get the data type of the object

1. int Integers
characteristic : immutable 、 disorder

Representation :a=1

Available function methods :


# Look at the length of bytes occupied , Almost no use
ret = int.bit_length(333)
print(ret) --->9
# Convert a decimal to an integer
int(12.34) ---> 12
# It's often used for base conversion
Binary system :1 And 0 form ,0b It begins with
octal :0~7 form , Meet 8 Into the 1,0o start
Decimal system :0~9 form , Meet 10 Into the 1,
Hexadecimal :0~9~a~f form ,0x start
The principle of Radix conversion , First of all n Turn into 10 Base number , And then call the relevant methods for the corresponding binary conversion
bin(n) take n Turn into 2 Base number
oct(n) take n Turn into 8 Base number
hex(n) take n Turn into 16 Base number
take 2 The base number is converted to 10 Base number
int(n,2)
take 2 The base number is converted to 8 Base number
oct(int(n,2))
take 2 The base number is converted to 16 Base number
hex(int(n,2))
take 8 The base number is converted to 2 Base number
bin(int(n,8))
take 10 The base number is converted to 2 Base number
bin(int(n))
take 16 The base number is converted to 2 Base number
bin(int(n,16))
# Example
Generate a 5 Bit verification code ?
import random
verify_num = ''
for i in range(5):
int_num = random.randint(0, 9) # take [0,9]10 A digital
# int_num = chr(random.randint(48,57)) # You can also get 0~9
lstr_num = chr(random.randint(65, 90)) # take ascii Code table corresponding to a~z,chr(num) Convert numbers to ascii The corresponding letters in
ustr_num = chr(random.randint(97, 122)) # Take the corresponding A~Z
choice_list = [int_num, lstr_num, ustr_num] # Build a list of numbers and letters
v = str(random.choice(choice_list)) # Choose one at random
verify_num += v
print(verify_num)

2. bool Boolean
characteristic : immutable , disorder , Don't slice

Representation :False,True

# python It is used to judge the condition
>=1 The integer of , Or variables with values are true True,0,None,"",list(),tuple(),dict(),set() All for False

3. str character string
characteristic : immutable 、 Orderly 、 Slicing 、 Can the iteration 、 Don't add, delete, or alter , The default output of interaction is string

Representation :a='xxx' or a="xxx"

Common methods available :

# section : From left to right , The index in the string is from 0 Start [ The starting position : Cut off position : span ] Head and tail
"china"[1:3] Means get from index 1 To 2 The characters of , The result is :hi
"china"[1:-1] Identity gets from index 1 To the penultimate character (-1 Represents the last character in the slice ), The result is :hin
del string Delete string
len(string) Statistical string length
str.count(s) Statistics s The number of times an element appears
string.capitalize() Start with a capital letter
string.upper() All strings are capitalized
string.lower() All strings are lowercase
string.startswith(" Elements ") Whether the string starts with the specified element
string.endswith(" Elements ")
string.find(" Elements ",start,end) Gets the index of the specified element , If the element does not exist , return -1
string.index(" Elements ",start,end) ditto , But the element doesn't exist , Throw an exception
string.strip(" Elements , The default is empty. ") Delete the specified element on both sides of the string , Remove spaces on both sides when no element is specified
string.split(" Separator element , Default space , Multiple spaces are considered as one ") Separate strings with specified elements , Return a list
string.replace(old,new, Replace it a few times ) Replace the elements in the string with new ones
string.zfill(n) The string length is not enough for the specified n length , Then the left side of the default string is supplemented with 0, Binary will use
# take IP:192.168.0.100 Convert to binary
ip = "192.168.0.100"
bin_list = []
for i in ip.split("."):
s = bin(int(i))[2:].zfill(8)
bin_list.append(s)
bin_string = ".".join(bin_list)
print(bin_string) ---> 11000000.10101000.00000000.01100100
# String formatting
0. + Splicing
"my name" + "is sun" --->"my name is sun"
1. string.format()
"{} my name is:{}".format(2021,"sun")
"{1} my name is {2},last number is {1}".format(2021,"sun")
"{year} is niu, my name is {name}".format(year=2021,name="sun")
"{year} is niu, my name is {name}".format(**{"year":2021,"name":"sun"})
2. % Percent sign
%s Representation string
%d Represents an integer
%f It's a decimal %.2f Retain 2 Decimal place
"my name is %s,age is %d" % ("china","30")
"my name is %(name)s,age is %(age)d" % {"name":"sun","age":30}
3. python edition >=3.6 when , adopt f"{ Variable }is my name" Faster formatting
4. " Splicer ".join( Iteratable object ) Each element of an iteratable object is bridged by a splice , Splice into a new string
".".join(["192","168"]) ---> "192.168"
"$".join([11,22]) In this case, an error is reported ,join You can't put numbers together , It needs to be converted to a string before splicing
"$".join("%s" %id for id in [11,22]) ---> "11$22"

4. list list
characteristic : variable 、 Orderly 、 Slicing 、 Can the iteration 、 The element can be any element 、 It can be added, deleted, modified and checked

Representation :a=[] or a=list()

Available methods :

 section :
Method is the same as string slicing by index
increase :
list_obj.append( Elements ) Add elements to the end of the list
list_obj.insert( Elements , Elements ) Add elements to the list at the specified index location
list_obj.extend( Iteratable object ) Add multiple elements to the end of the list
Delete 【 There is no return value after deletion 】:
list_obj.pop( Indexes ) Delete the element at the specified position in the list , If the index does not exist , Throw an exception
list_obj.remove( Elements ) Deletes the specified element in the list , If the element does not exist , Throw an exception
del list_obj Delete list objects from memory
del list_obj[:3] Slice delete based on index
list_obj.clear() clear list
Change :
Slice modification :list_obj[index] = new_data
li =[11,22,33,44,55]
li[:2]=[66,77,88,99] # li=[66,77,88,99,33,44,55] In steps of 1 when , Regardless of the number correspondence , It's a piece of space
li[:3:2] = [10,20] # A long way to go 1 when , The number of left and right elements should be consistent , So this expression , Throw an exception to report an error
check :
list_obj[index] Look up through the index
for i in list_obj Check through iteration ,i For each element in the list
Common methods :
del list_obj Delete list
len(list_obj) Count the number of list elements
list_obj.count( Elements ) Count the number of occurrences of elements
list_obj.index(object,start,end) Find the index of the element
list_obj.sort(reverse=False) Sort , The default is ascending , When reverse Value to True when , Descending order , Only when the elements in the list are the same can , Otherwise an error
list_obj.reverse() Reverse the order of the elements in the list , Same as above sort Operate on list objects as well , Directly , There will be no return value
list_obj.copy() A shallow copy of the list
object in list_obj Determine whether the object is in the list
Enumeration functions enumerate
for i in enumerate(list_obj):
print(i) --->( Indexes , Elements )

5. tuple Yuan Zu
characteristic : immutable 、 Slicing 、 Can the iteration 、 Orderly 、 The element can be any element 、 Don't add, delete, or alter

Representation :t=() or t=tuple()

notes :

If there is only one element , Add a comma at the end , Otherwise python Think of it as a variable or do mathematical operations, etc , Such as t=(10000,)

The first layer of data in Yuanzu is immutable , If the second level data type is variable (list,dict,set) It's variable , Such as t=(1,[1,2,3],{4,5,6},{"a":1,"b":2})

t=1, python I think it's also an element

Available methods :


# check
tuple_obj[2] By slicing
for t in tuple_obj:pass Check through iteration
del tuple_obj
len(tuple_obj) Count the length of the object
tuple_obj.count( Elements ) Count the number of occurrences of elements
tuple_obj.index( Elements ) Get the index of the element
# deconstruction
a,b = (3,6)
--> a=3,b=6
The number of elements on the left must be the same as that on the right , alike str,list,dict They all have this characteristic 

6. dict Dictionaries
characteristic : variable (key immutable , Variable value )、 disorder (3.6 It's all in order )、 Can the iteration 、 Value elements can be of any data type 、 It can be added, deleted, modified and checked

Representation :d={key:value} or d=dict()

# increase
dict_obj[key]=new_data If key If it doesn't exist, add , If it exists, update the corresponding key Value
dict_obj.setdefault("key", default=" The default value is ")
Newly added key, If in dict_obj There is already , It will not change the original value, Otherwise add
setdefault There is a return value , The return value is value, If it's time to key There is , What is returned is the original value , If it doesn't exist, return the default value
d = {"test":111}
d.setdefault("test",2222)
print(d) ---> {"test":111}
# Example : Will list li=[1,2,3,4,5,6,7,8] With 3 Separate into two dictionaries {"k1":[ Less than 3 Value ],"k2":[ Greater than or equal to 3 Value ]}
d = {}
for i in li:
if i < 3:
d.setdefault("k1", []).append(i)
else:
d.setdefault("k2", []).append(i)
print(d) ---> {'k1': [1, 2], 'k2': [3, 4, 5, 6, 7, 8]}
dict.fromkeys(iterale,value)
Each element in the preceding iterative sequence , All the same as the values set later , Form a key Different ,value The same dictionary
If the latter value Is a variable data type , So change any dictionary of sequence elements value, Other elements change as well
It's just a shallow copy
# Example
s = dict.fromkeys("key", [11, 22])
print(s) # ---> {'k': [11, 22], 'e': [11, 22], 'y': [11, 22]}
s["k"][0] = 333
print(s) # ---> {'k': [333, 22], 'e': [333, 22], 'y': [333, 22]}
s["k"] = "xxxx"
print(s) # ---> {'k': 'xxxx', 'e': [333, 22], 'y': [333, 22]}
# Delete
dict_obj.pop(key) Delete the specified key, Return the corresponding deleted value, Delete the last item by default , If key non-existent , Report errors
dict_obj.popitem() python3.6 Randomly delete before version , After that, the last key value pair is deleted by default , Return the key value pair of Duyin in the form of Yuanzu
del dict_obj[key]
del dict_obj
dict_obj.clear()
# Change
dict_obj[key]=new_data
dict_obj.update(dict_obj) No return value !!!, Two dictionaries merge , If there is key identical , Then the back covers the front
# check
dict_obj[key] key When there is no , Report errors
dict_obj.get(key," The default value is ") key When there is no , Return default , When the default value is not set, the default value is None
dict_obj.items() Returns a key value pair displayed as a primitive
dict_obj.keys() Return to all of the key, Can the iteration
dict_obj.values() Return to all of the values, Can the iteration
for k in dict_obj k by dict_obj Every key of the
len(dict_obj) Count the number of dictionaries 

7. set aggregate
characteristic : variable 、 disorder 、 Don't slice 、 Can the iteration 、 The element needs to be a unique, non repeating and hash invariant data type

Representation :s={1,2,3} or s=set()

notes : Sets can be used to de duplicate , And the differences and the same parts when analyzing the data


# increase
set_obj.add( Elements ) No return value
set_obj.update(iterale) The sequence iteratively updates to set in
# Delete
set_obj.pop() Random delete , Return the deleted value
set_obj.remove( Elements ) No return value , There are no misstatements
set_obj.clear()
del set_obj
# Change
Because of disorder , Only by deleting the specified element first , Then add new elements
set_obj.remove( Elements )
set_obj.add( Elements )
# check
for s in set_obj
# Find the number of elements
len(set_obj)
# Find the intersection of two sets ( The same part )
set_obj1 & set_obj2
# Find the union of two sets ( Merge together )
set_obj1 | set_obj2
# Find the difference set of two sets ( Remove the elements from the previous set that appear in the later set )
set_obj1 - set_obj2
# Find if it is a subset ( The front set is part of the back set )
set_obj1.issubset(set_obj2)
8. Conversion between data types
Turn a string into a number
# Want to put str convert to int,str It has to be all numbers , Otherwise an error
s = "1111"
s_to_int = int(s)
String to list
string.split()
list(string)
list & Yuan Zu & Set into a string
"".join(iterale)
Except for the dictionary 2 The relationship between two key value pairs cannot be transformed by class method , Strings can be iterated through list(),tuple(),set() Method to the corresponding data type
Same data type merge
# character string
It can be done by + 、format()、%、f"{}{}"
# list
+、extend()
# Dictionaries
update()
# aggregate
update()

9. List and dictionary elements deleted
When deleting a dictionary or a list , Changed the index of the list , The length of the dictionary , This may lead to failure to achieve the goal or report an error

# The elements to be deleted are stored in the temporary table , Traverse the temporary table , Delete the original list
base_list = [x,xx,xxx,xxxx]
base_dict = {k1:v1,k2:v2}
del_temp= [obj1,obj2]
for d in del_temp:
# List delete
base_list.remove(d)
# Dictionary delete
base_dict.pop(d)

10. Orderly dictionary
from python3.6 Start , The dictionary was created in order , But it's by create time key It's defined by the location of , An orderly dictionary is often used at work , Like verifying signatures , It is often necessary to put the request body json Sort them in a certain order and then code them

# Press the dictionary ASCII The code table is sorted in reverse order , Make a new dictionary
Scheme 1 :
import json
ret = json.dumps(data, sort_keys=True)
Option two :
message json Nested hierarchy 2 layer :
def base_sort(data):
for k, v in data.items():
if isinstance(v, dict):
second_sort = sorted(v, reverse=True)
gen_dict = {j: v[j] for j in second_sort}
# Back to the end of the sequence
data[k] = gen_dict
else:
data = {i: data[i] for i in sorted(data, reverse=True)}
return data
message json Level nesting 3 Layers or more ?
python It comes with an ordered dictionary :OrderedDict
"""python An ordered Dictionary of , It is output in the order of dictionary insertion """
from collections import OrderedDict
d = OrderedDict()
d["a"] = "a"
d["b"] = "b"
d["c"] = "c"
for k, v in d.items():
print(k, v)

11. enumeration
Enumeration guarantees key And value Uniqueness , It's often used to build enumeration dictionaries at work , Construction of state response specification

# Enumeration functions :enumerate(iterable,start=0), Output the index and value of the element in the form of ancestor
for index,value in enumerate(li):
print(index,value)

Request construction service response status code enumeration class ?

# Scheme 1
class ErrorEnumV1(object):
code0 = (0, " success ")
code2 = (1, " Failure ")
code3 = (2, " Parameter exception ")
# Option two : Optimize 【 Guarantee key And value Uniqueness , Otherwise an error 】
from enum import Enum, unique
@unique
class StateEnum(Enum):
code0 = (0, " success ")
code2 = (1, " Failure ")
code3 = (2, " Parameter exception ")
if __name__ == '__main__':
# obtain code and desc
code = StateEnum.code0.value[0]
desc = StateEnum.code0.value[1]
print(code, desc)

12. Depth copy
Shallow copy :

1、 For variable data types :list、dict、set , Immutable data types int、str、tuple、bool There is no copy of it , None of them copy() Method

2、 After the shallow copy, a new address is allocated in the memory address , And the shallow copy only copies the first layer , The second layer doesn't copy , So if the second level changes , The original data and shallow copy data will also change

3、= Assignment is not a shallow copy

a = [11,22,[11,22]]

b = a

notes : The above is called assignment , Just to a,b They all point to the same memory address

a.append(33)

print(b) ---> [11,22,[11,22],33] Or change together ,b and a Both are aliases of the memory address of the list

c = a.copy() Method of use copy Is a shallow copy ,id(a) And id(c) The memory address of is different
4、[:] Slices are light copies


lis = [11,22,[11,22]]
qie = lis[:]
lis[2].append(33)
print(lis,qie) # [11, 22, [11, 22, 33]] [11, 22, [11, 22, 33]]
print(id(lis),id(qie)) # 1482689615624 1482689615752
Deep copy :
That is to copy the internal elements of the original file completely , It won't change because of the second element , The other will change
Deep copy method :
import copy
list_new = copy.deepcopy()
# In this method, if you change the message content in the process of processing the request message ,
# Remember to make a deep copy first , Or you'll be a platoon bug It's a headache
```!