Catalog
Empty dictionary declaration method
Common declaration method (key: value = 1:1)
Add a new key value pair to the dictionary
Common loop traversal and output the value of the corresponding key
Dictionary operation: sorting and updating
Sorting values and keys in tuples
More concise sorting by referencing the itemgetter package
Common list declaration method
The difference between append function and extend function
Normal array declaration method
Generate evenly distributed array
Array traversal is the same as list traversal
I. dictionary
-
Declaring dictionary
-
Empty dictionary declaration method
dict = {}
-
Common declaration method (key: value = 1:1)
#One-dimensional dict = {key1 : value1, key2 : value2 } #Multidimensional dict_2d = {'a': {'a': 1, 'b': 3}, 'b': {'a': 6}}
-
Add a new key value pair to the dictionary
#One-dimensional dict.setdefault(key,value) #Two-dimensional def addtodict2(thedict, key_a, key_b, val): if key_a in thedict: thedict[key_a].update({key_b: val}) else: thedict.update({key_a:{key_b: val}}) #Multidimensional def addtodict3(thedict,key_a,key_b,key_c,val): if key_a in thedict: if key_b in thedict[key_a]: thedict[key_a][key_b].update({key_c:val}) else: thedict[key_a].update({key_b:{key_c:val}}) else: thedict.update({key_a:{key_b:{key_c:val}}})
(if you want a value to correspond to multiple values, you can set the value to a list or array)
-
Dictionary format:
-
The key must be unique, but the value is not.
-
Value can take any data type, but the key must be immutable
-
Traversal of dictionaries
-
Common loop traversal and output the value of the corresponding key
#One-dimensional #General loop traversal for key, value in dict.items(): print(key+':'+str(value)) #Output the value corresponding to the keyword print(dict[key]) #Multidimensional for key1 in thedict: for key2 in thedict[key1]: for key3 in thedict[key1][key2]: print (key3+":"+str(thedict[key1][key2][key3]))
-
Traverse the value of each key horizontally, and get a maximum value (one dimension) for each completed row
maxvaluelist=[] maxkeylist=[] valuelength=0 for k,v in data.item():Get once data Of value Length valuelength = len(v) break for i in range(0,valuelength):#The start and end of traversal is the length of 0-valuelength maxvalue=0 maxkey='' for k,v in data.item():#Traverse every key if v[i]>maxvalue : maxvalue = v[i] maxkey = k else continue maxvaluelist.append(maxvalue) maxkeylist.append(maxkey)
-
Traverse the value of each key longitudinally, and get a maximum value (one dimension) for each completed column
maxvaluelist={} for k,v in data.item():#Traverse every key maxvalue = 0 for item in v: if item>maxvalue : maxvalue = item else: continue maxvaluelist.setdefault(k,maxvalue)
-
Dictionary operation: sorting and updating
-
Sort by key
#Forward sort dict1={'a':2,'e':3,'f':8,'d':4} dict2 = sorted(dict1) print(dict2) #output >>['a', 'd', 'e', 'f'] #Reverse sorting dict1={'a':2,'e':3,'f':8,'d':4} dict2 = sorted(dict1,reverse=True) print(dict2) #output >>['f', 'e', 'd', 'a']
-
Ranking by value
dict1={'a':2,'e':3,'f':8,'d':4} list1= sorted(dict1.values()) print(list1) #output >>[2, 3, 4, 8] #Set reverse=True to reverse sort
-
Sorting values and keys in tuples
#Use dict1.items() to get the tuple containing key and value #Since the iteration object is a tuple, the return value is naturally a list of tuples #Here, the sorting rules are defined: X refers to tuple, x[1] is value, x[0] is key) dict1={'a':2,'e':3,'f':8,'d':4} list1= sorted(dict1.items(),key=lambda x:x[1]) print(list1) #output >>[('a', 2), ('e', 3), ('d', 4), ('f', 8)] #Similarly, key sorting includes: dict1={'a':2,'e':3,'f':8,'d':4} list1= sorted(dict1.items(),key=lambda x:x[0]) print(list1) #output >>[('a', 2), ('d', 4), ('e', 3), ('f', 8)]
-
More concise sorting by referencing the itemgetter package
from operator import itemgetter d = {"a":8,"b":4,"c":12} print(sorted(d.items(),key=itemgetter(0),reverse=True)) print(sorted(d.items(),key=itemgetter(1),reverse=True)) #itemgetter(0), get key #itemgetter(1), get value #output >>[('c', 12), ('b', 4), ('a', 8)] >>[('c', 12), ('a', 8), ('b', 4)]
-
Update with updata function
# Pass in a dictionary and change the original value d = {'one':1,'two':2} d.update({'one':3,'two':4}) print(d) >>{'one': 3, 'two': 4} # Pass in a dictionary and add a new key value pair d = {'one':1,'two':2} d.update({'three':3,'four':4}) #Or we can use its equivalent #d.update(three=3,four=4) #d.update([('three',3),('four',4)]) print(d) {'four': 4, 'one': 1, 'three': 3, 'two': 2}
Two, list
-
Declaration list
-
Empty list declaration method
list = []
-
Common list declaration method
list1 = ['Beijing', 'Shenzhen', 1998, 2020]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];
-
Add new values to the list
list.append(value)
-
The difference between append function and extend function
#Using append a = [1, 2, 3] b = [4, 5, 6] a.append(b) print(a) #output >>[1, 2, 3, [4, 5, 6]] #Using extend a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a) //output >>[1, 2, 3, 4, 5, 6]
-
List format:
Data items of the list do not need to have the same type
-
Traversal of list
-
Traverse directly by range
#One-dimensional for i in range(0,len(list)): print(list(i)) #Two-dimensional for i in range(0,len(list)): for j in range(0,len(list[i]): print(list[i][j])
-
Traversal by element
#One-dimensional for item in list: print(item) #Two-dimensional for x in list: for y in x: print(y)
-
List operation: cut, splice
-
List cut
list=['123','abc',0,True] x=list[1:] y=list[:3] z=list[2:3] print(x) print(y) #output >>['abc', 0, True] >>['123', 'abc', 0] >>[0] #Add step length #Format: variable [head subscript: tail subscript: step size] list=['123','abc',0,True,"12345"] x=list[1:4:2] print(x) #output >>['abc', True]
-
List stitching
list1 = [1,2,3] list2 = [4,5,6] #Use + splicing newlist = list1+list2 print(newList) #output >> [1,2,3,4,5,6] #----------------------------- #Slicing and stitching newList=list1 newList[len(list1),len(list2)] = list2 #output >> [1,2,3,4,5,6] #----------------------------- #Use extend as mentioned above
Three, array
-
Declare array mode
-
Normal array declaration method
#One-dimensional np.array([2,3,4]) #Multidimensional np.array([2,3,4],[5,6,7])
-
Declare zero array
np.zeros( (3,4) ) #output >>>array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
-
Declare all 1 array ones
np.ones( (2,3,4), dtype=np.int16 ) # dtype can also be specified >>array([[[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]], [[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]]], dtype=int16)
-
Declare random number array
np.empty( (2,3) ) # uninitialized, output may vary >>array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]])
-
To generate a evenly distributed array:
Range (min, Max, step) (left closed right open)
linspace (min, Max, number of elements)
np.arange( 10, 30, 5 ) #output >>array([10, 15, 20, 25]) np.arange( 0, 2, 0.3 ) # it accepts float arguments #output >>array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]) np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2 #output >>array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
-
Format of array:
ndarray.ndim: dimensions of an array
ndarray.shape: the size of each dimension of the array
ndarray.size: the number of all elements in the array
ndarray.dtype: the type of elements in the array (numpy.int32, numpy.int16, and numpy.float64, etc.)
ndarray.itemsize: several bytes per element
-
The traversal of an array is the same as that of a list
-
Traverse directly by range
#One-dimensional for i in range(0,len(list)): print(list(i)) #Two-dimensional for i in range(0,len(list)): for j in range(0,len(list[i]): print(list[i][j])
-
Traversal by element
#One-dimensional for item in list: print(item) #Two-dimensional for x in list: for y in x: print(y)
-
Array operation: cut, splice
-
The array is first converted to a list, then cut and spliced in the form of a list, and then converted back to an array.
#List & matrix to array array = np.array(list) array = np.array(matrix) # List & array transformation matrix matrix = np.mat(list) matrix = np.mat(array) # Array & matrix to list list = array.tolist() list = matrix.tolist()
-
shape and reshape of array
import numpy as np #Use of shape a = np.array([1,2,3,4,5,6,7,8]) #One-dimensional array print(a.shape[0]) #The value is 8 because there are 8 data print(a.shape[1]) #IndexError: tuple index out of range a = np.array([[1,2,3,4],[5,6,7,8]]) #Two-dimensional array print(a.shape[0]) #The value is 2, the outermost matrix has 2 elements, 2 elements or matrix. print(a.shape[1]) #The value is 4, and the inner matrix has four elements. print(a.shape[2]) #IndexError: tuple index out of range #Usage of reshape a = np.array([1,2,3,4,5,6,7,8]) #One-dimensional array a_2d = a.reshape(2,4) #output >>[[1,2,3,4], [5,6,7,8]] a_3d = a.reshape(2,2,2) #output >>[[[1,2],[3,4]],[[5,6],[7,8]]]
The above is the basic knowledge accumulated by all bloggers about dictionaries, arrays and lists. Hope to help you!