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

6.1_ 4 Python3. X entry P4 [basic] variable sequence (list, dictionary dict, set set)

編輯:Python

Related links

  • Catalog
  • Mac M1 Python Environment building
  • Python3.x introduction P1 【 Basics 】 notes 、 identifier 、 Variable 、 data type
  • Python3.x introduction P2 【 Basics 】 Operator
  • Python3.x introduction P3 【 Basics 】 Process statement 【 Loop structure 】
  • Python3.x introduction P4 【 Basics 】 Variable sequence ( list list、 Dictionaries dict、 aggregate set)
  • Python3.x introduction P5 【 Basics 】 Immutable sequence ( Tuples tuple、 character string str)
  • Python3.x introduction P6 【 String formatting 】 Four ways ( Manual 、%-formatting、str.format()、f-String)
  • Python3.x introduction P7 【 function 】

One 、 Sequence

Variable sequence : The execution sequence can be incremented 、 Delete 、 Change operation , The object address does not change .

① list list -> [v1,v2,…]、② aggregate set -> {k1,k2,…}、③ Dictionaries dict -> {k1:v1,…}

Immutable sequence : No increase 、 Delete 、 Change the operation . Because of its immutable nature , In a multithreaded scenario , No need to lock .

① Tuples tuple -> (v1,v2,…) 、② character string str -> ‘’


1.1 Variable sequence & Immutable sequence

""" @author GroupiesM @date 2022/6/22 16:11 @introduction Variable sequence : list list、 Dictionaries dict、 aggregate set The execution sequence can be incremented 、 Delete 、 Change operation , The object address does not change Immutable sequence : Tuples tuple、 character string str No increase 、 Delete 、 Change the operation """
''' Variable sequence list list、 Dictionaries dict、 aggregate set'''
lst = [10, 20, 45]
lst.append(300)
print(lst) # [10, 20, 45, 300]
''' Immutable sequence Tuples tuple、 character string str'''
t = ('python', 5)
print(t) # ('python', 5)

1.2 Immutable sequence & Multithreading

""" @author GroupiesM @date 2022/4/29 09:25 @introduction Immutable sequence ( Tuples 、 character string ) In the scenario of multiple threads , There is no need to lock when operating the same object at the same time matters needing attention : Tuples store references to objects a) If the object itself in the tuple is immutable , That is, the memory address pointed to is immutable b) If the object in the tuple is a non basic type , You can modify the data """
t = (10, [20, 30], 9)
print(t) # (10, [20, 30], 9)
''' When the element in a tuple is a reference type , You can modify the data of the reference type '''
t[1].remove(30) # (10, [20], 9)
print(t) # (10, [20], 9)
''' The memory address of the element cannot be modified '''
t[1] = [50]
print(t) # TypeError: 'tuple' object does not support item assignment

1.3 summary

data structure Variable sequence The value is repeatable Is it orderly Defining symbols list (list)√√√[v1,v2,…] aggregate (set)√××{k1,k2,…} Dictionaries (dict)√key(×) value(√)×{k1:v1,k2:v2,…} Tuples (tuple)×√√(v1,v2,…)

P.S:
1. Immutable sequences do not change in memory

2. If you make a change to an immutable sequence , The sequence will be stored in the new address space , And the original sequence because of the garbage collection mechanism , Will be recycled .

3. When the variable sequence changes , Will not change the address , Instead, change the value in memory , Or expand memory space .

4. Dictionaries Is a variable sequence , But the keys of the dictionary are immutable , And the value is variable . Because the principle of dictionary structure is the hash table of pseudo-random detection , It looks up by passing a key through a hash function , Find the memory address of the value . Therefore, the hash value is generally unique or the conflict is relatively small . If you change the value of the key ,name The hash value will change , The original value cannot be found , So the value of the key is immutable . After the key hash, it points to the address in memory , Changes in the data in memory do not affect the search of the dictionary .


Two 、 list list -> [v1,v2,…]


2.1 brief introduction

""" @author GroupiesM @date 2022/4/28 09:26 @introduction <class 'list'> list :list = ['hello', 'world', 100] aggregate : set = {'python', 'hello', 90} Dictionaries :dict = {'name': ' Zhang San ', 'age': 100} Tuples :tuple = ('python','hello',90) character string : str = 'python' """
lst = ['hello', 'world', 100]
print(type(lst)) # <class 'list'>
print(lst) # ['hello', 'world', 100]

2.2 establish

""" @author GroupiesM @date 2022/4/28 09:36 @introduction List creation method : Mode one : Use brackets [], Elements are separated by English commas list = ['hello','python'] Mode two : Built in functions list() Type conversion list(('hello','php')) # list -> list list({'name': ' Zhang San ', 'age': 100}) # Dictionaries -> list list(['hello','php']) # Tuples -> list list({'python', 'hello', 90}) # aggregate -> list list('hello') # character string ->list """
''' Mode one '''
lst = ['hello', 'python', 13]
print(lst) # ['hello', 'python', 13]
''' Mode two '''
'''1.list->list'''
lst1 = list(('hello', 'php')) # list -> list
print('lst1', lst1) # ['hello', 'php']
'''2. Dictionaries ->list when , Take the dictionary automatically key'''
lst2 = list({
'name': ' Zhang San ', 'age': 100}) # Dictionaries -> list
print('lst2', lst2) # ['name', 'age']
'''3. Tuples ->list'''
lst3 = list(['hello', 'php']) # Tuples -> list
print('lst3', lst3) # ['hello', 'php']
'''4. aggregate ->list'''
lst4 = list({
'python', 'hello', 90}) # aggregate -> list
print('lst4', lst4) # [90, 'python', 'hello']
'''5. character string ->list'''
lst5 = list('hello') # character string ->list
print('lst5', lst5) # ['h', 'e', 'l', 'l', 'o']

2.3 characteristic

""" @author GroupiesM @date 2022/4/28 09:41 @introduction 1. The elements are in order 2. Each index maps unique data 3. The value is repeatable 4. Mixed storage of any data type 5. Dynamically allocate and reclaim memory as needed 6. Basic types : Value at the same time , The memory address is the same 7. Reference type : Value at the same time , Memory address is different P.S len() Get object length , Cannot be used for int,float,bool type """
list = ['hello', 'hello', [' Zhang San ', ' Li Si '], [' Zhang San ', ' Li Si '], 50, True]
print(len(list)) # 5
for i in range(0, len(list)):
print(list[i], end="\t")
'''hello hello [' Zhang San ', ' Li Si '] [' Zhang San ', ' Li Si '] 50 True '''
print()
for i in range(0, len(list)):
print(id(list[i]), end="\t")
''' hello It appears twice , Twice id All are 4310643824 [' Zhang San ', ' Li Si ']: Twice ,id It's different 4310643824 4310643824 4312636928 4312643456 4321732376 4321512264 '''

2.4 list[n] lookup Indexes -> value

""" @author GroupiesM @date 2022/4/28 10:10 @introduction Indexes -> value : Forward index from 0 To n-1 list[0] -> list[n-1] Reverse index from -n To -1 list[-n] -> list[-1] The specified index does not exist , Throw out IndexError """
list = ['hello', 'python', 'python', 50, True]
print('-------- Forward index traversal --------')
for i in range(0, len(list)):
print(list[i], end="\t") # # hello python python 50 True
print('\n-------- Reverse index traversal --------')
for i in range(-len(list), 0, 1):
print(list[i], end="\t") # hello python python 50 True

2.5 list.index() lookup value -> Indexes

""" @author GroupiesM @date 2022/4/28 09:55 @introduction index(): If there is... In the list n Same elements , Only the index of the first element in the same element is returned If the element of the query does not exist in the list , It will be thrown out. ValueError You can also specify start,stop Find in index range """
list = ['hello', 'python', 'python', 50, True]
''' index: 0 1 2 3 4 ['hello', 'python', 'python', 50, True] '''
num: int = list.index('python')
print(num)
'''1'''
num: int = list.index(50)
print(num)
'''3'''
num: int = list.index('50')
print(num)
'''ValueError: '50' is not in list'''

2.6 section -> Get new list

""" @author GroupiesM @date 2022/4/28 10:15 @introduction Get multiple elements in the list Grammar format : List name [start:stop:step] Slicing operation : The result of the slice : Original list slice , Form a new list The extent of the slice :[start,stop) step The default is 1: Shorthand for [start:stop] step Is a positive number : from start Start counting slices back [:stop:step]: The first element of the slice defaults to the first element of the list [start::step]: The last element of the slice defaults to the last element of the list step It's a negative number : from start Start counting slices forward [:stop:step]: The first element of the slice defaults to the last element of the list [start::step]: The last element of the slice defaults to the first element of the list """
# 0 1 2 3 4 5 6 7 8 9 Forward index 
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# -9 -8 -7 -6 -5 -4 -3 -2 -1 0 Reverse index 
''' Index length '''
print(len(list)) # 10
'''step The default is 1'''
print(list[1:8]) # [2, 3, 4, 5, 6, 7, 8]
print(list[1:-2]) # [2, 3, 4, 5, 6, 7, 8]
'''step Is a positive number '''
print(list[:10:2]) # [1, 3, 5, 7, 9]
print(list[0::2]) # [1, 3, 5, 7, 9]
'''step Is a negative number '''
print(list[:-10:-2]) # [10, 8, 6, 4, 2]
print(list[10::-2]) # [10, 8, 6, 4, 2]

2.7 Judge in&not in

""" @author GroupiesM @date 2022/4/28 11:12 @introduction Determine whether the specified element exists in the list Elements in List name Elements not in List name """
list = [10, 20, 30, 40]
print('p' in 'python') # True
print(10 in list) # True
print(15 in list) # False
print('abc' not in list) # True

2.8 Traverse

""" @author GroupiesM @date 2022/4/28 11:30 @introduction Traversal of list elements for Iterate through in List name operation """
list = [1, 2, 3, 4]
print("---- Mode one ------")
for i in list:
print(i, end="\t") # 1 2 3 4
print("\n---- Mode two ------")
for i in range(len(list)):
print(list[i], end="\t") # 1 2 3 4

2.9 Added 5 Ways of planting

1. append(Object obj): Add an element at the end of the list .

2. extend(Iterator iter): Add an element at the end of the list .( After traversing all the elements , Add the elements )

3. insert(Integer i,Object obj): Add an element at the specified position in the list .

4. lst[ section ]: Slice the list first , Add again ele.lst[start:stop:step]: The three parameters can be left blank .

5. +: Add two lists .

P.S :Object = Any type ; Iterator = Iterator type


2.9.1 append()- Add element to end

""" @author GroupiesM @date 2022/4/28 11:38 @introduction append(Object obj): Add an element at the end of the list . """
''' Additive elements - Basic types '''
lst = [10, 20, 30]
lst.append(40)
lst.append(50)
print(lst, id(lst)) # [10, 20, 30, 40, 50] 4378974400 lst Reassign ,id Change 
''' Additive elements - list '''
lst = [10, 20, 30]
tmp = [40, 50]
print(lst, id(lst)) # [10, 20, 30] 4377304000
lst.append(tmp)
print(lst, id(lst)) # [10, 20, 30, [40, 50]] 4377304000,id It hasn't changed , The description is the original list 

2.9.2 extend()- Traverse the element and add to the end

""" @author GroupiesM @date 2022/4/28 11:39 @introduction extend(Iterator iter): Add an element at the end of the list .( Go through all the elements ) """
''' Additive elements - Basic types (x) extend Only applicable to iterator type elements '''
lst = [10, 20, 30, 40]
try:
lst.extend(50)
except Exception as e:
print(e) # 'int' object is not iterable
print(lst)
''' Additive elements - list (v) The list belongs to an iterator '''
lst = [10, 20, 30, 40]
tmp = [40, 50]
lst.extend(tmp)
print(lst)

2.9.3 insert()- Add elements to the specified location

""" @author GroupiesM @date 2022/4/28 13:46 @introduction insert(Integer i,Object obj): Add an element at the specified position in the list . """
''' Additive elements - Basic types In the index 0 Add an element to the location of 'a' '''
lst = [10, 20, 30]
print(lst, id(lst)) # [10, 20, 30] 4305885440
lst.insert(0, 'a')
print(lst, id(lst)) # ['a', 10, 20, 30] 4305885440
''' Additive elements - list In the index 0 Add a list to the location of ['a','b'] '''
lst = [10, 20, 30]
tmp = ['a', 'b']
print(lst, id(lst)) # [10, 20, 30] 4305886272
lst.insert(0, tmp)
print(lst, id(lst)) # [['a', 'b'], 10, 20, 30] 4305886272

2.9.4 section ( And replace )

""" @author GroupiesM @date 2022/4/28 13:33 @introduction lst[ section ] = ele<iter>: Slice the list first , Add again 1) lst[start:stop:step] = ele<iter> : 1.1 Replace operation 1.2 Number of elements replaced , And the number of elements replaced , Be equal 1.3 among start,stop,step Can be left blank , The default values are 0,len(lst),1 2) lst[start:stop] = ele<iter>: among start,stop Can be left blank , The default values are 0,len(lst) 2.1 Replace operation 2.2 Number of elements replaced , And the number of elements replaced , Equality is not required 2.3 among start,stop Can be left blank , The default values are 0,len(lst) 3) lst[start:start] = ele<iter>: On top of that ,start and stop Have the same value , It is equivalent to the insertion effect difference : In the first way, the number of elements should be consistent , The number of elements before and after the second method is not required """
''' 1) Replace operation [start:stop:step] From the index 0 Start , Index every +2 Perform a replacement operation , A total of 10/2=5 Time '''
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd', 'e']
lst[0:len(lst):2] = tmp
print(lst) # ['a', 10, 'b', 30, 'c', 50, 'd', 70, 'e', 90]
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd', 'e']
# lst[::2] Equivalent to lst[0:len(lst):2]
lst[::2] = tmp
print(lst) # ['a', 10, 'b', 30, 'c', 50, 'd', 70, 'e', 90] , Same as the above test results , The two expressions are equivalent 
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd']
try:
lst[::2] = tmp
except Exception as e:
print(e)
""" attempt to assign sequence of size 4 to extended slice of size 5 Try to set the size to 4 The sequence of is assigned to a size of 5 Expansion piece """
print(lst)
''' 2) Replace operation [start:stop] 2.1) take 1-end, Replace with a new array 2.2) take 0-1, Replace with a new array '''
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd', 'e']
lst[1:] = tmp
print(lst) # [0, 'a', 'b', 'c', 'd', 'e']
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd', 'e']
lst[1:len(lst)] = tmp
print(lst) # [0, 'a', 'b', 'c', 'd', 'e']
''' 3) Add operation [start:start] 3.1) In the index 1 Insert the new array at the position of '''
lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
tmp = ['a', 'b', 'c', 'd', 'e']
lst[1:1] = tmp
print(lst) # [0, 'a', 'b', 'c', 'd', 'e', 10, 20, 30, 40, 50, 60, 70, 80, 90]

2.9.5 +

Two list You can add (+), But you can't subtract (-).

""" @author GroupiesM @date 2022/6/29 14:17 @introduction + : Add two lists """
lst1=[1,2,3,4,5,6]
lst2=[5,6,7,8]
print(lst1 + lst2)#[1, 2, 3, 4, 5, 6, 5, 6, 7, 8]

2.10 Delete the 5 Ways of planting

1. remove(Object obj): Delete the specified Value The elements of .
1) Delete one element at a time .
2) Duplicate elements delete only the first .
3)Value If it doesn't exist, throw ValueError.

2. pop(Integer i): Delete the specified index The elements of .
1) The specified index does not exist IndexError.
2) No index specified , Delete the last element in the list .

3. clear( ): clear list .

4. del lst: Delete element or list .
1) del lst_name[index]: Delete specified index .
2) del lst_name[start:end]: Delete elements according to the specified range
3) del lst_name[start:end :step] : Within the specified range 、 Interval delete elements
4) del lst_name : Delete list . Not just delete elements , The entire list does not exist after deletion .
The parameter start( Starting position )、end( End position )、step( step ) Can be omitted , When omitted, the default value is start=0,end=len(lst_name),step=1.

5. lst[ section ]: Slice the list .


2.10.1 remove()- Delete the specified Value

""" @author GroupiesM @date 2022/4/28 15:39 @introduction remove(): Delete the specified Value The elements of Delete one element at a time Duplicate elements delete only the first Value If it doesn't exist, throw ValueError """
lst = [10, 20, 30, 20, 10]
lst.remove(10)
print(lst) # [20, 30, 20, 10]
lst.remove(30)
print(lst) # [20, 20, 10]

2.10.2 pop()- Pop up the specified index location

""" @author GroupiesM @date 2022/4/28 15:39 @introduction pop(): Delete the specified index The elements of The specified index does not exist IndexError No index specified , Delete the last element in the list """
lst = [10, 20, 30, 20, 10]
lst.pop(1)
print(lst) # [10, 30, 20, 10]
lst.pop(11) # IndexError: pop index out of range

2.10.3 clear()- clear list

""" @author GroupiesM @date 2022/4/28 15:39 @introduction clear(): clear list """
lst = [10, 20, 30, 20, 10]
lst.clear()
print(lst) # []

2.10.4 del lst- Delete element or list

""" @author GroupiesM @date 2022/4/28 15:39 @introduction del: Delete element or list 1) del lst_name[index]: Delete specified index 2) del lst_name[start:end]: Delete elements according to the specified range 3) del lst_name[start:end:step] : Within the specified range 、 Interval delete elements 4) del lst_name : Delete list . Not just delete elements , The entire list does not exist after deletion . The parameter start( Starting position )、end( End position )、step( step ) Can be omitted , When omitted, the default value is start=0,end=len(lst_name),step=1 """
# 1) del lst_name[index]: Delete specified index 
lst = [10, 20, 30, 40, 50]
del lst[0]
print(1, lst) # [20, 30, 40, 50]
# 2) del lst_name[start:end]: Delete elements according to the specified range 
lst = [10, 20, 30, 40, 50]
del lst[:5] # Default start=0,end=5
print(2, lst) # []
# 3) del lst_name[start:end:step] : Within the specified range 、 Interval delete elements 
lst = [10, 20, 30, 40, 50]
del lst[0:3:] # Default step=1
print(3, lst)
# 4) del lst_name : Delete list ,
lst = [10, 20, 30, 40, 50]
del lst
# print(4,lst) # NameError: name 'lst' is not defined

2.10.5 section

""" @author GroupiesM @date 2022/4/28 15:39 @introduction section : Delete the specified [ Range ] The index of """
lst = [10, 20, 30, 20, 10]
lst = lst[::2] # from 0 Start , To the end ,index Every time +2, Intercept once 
print(lst) # [10, 30, 10]

2.11 Modifying elements

""" @author GroupiesM @date 2022/4/28 15:47 @introduction Modification of list elements Assign a new value to the element of the specified index Assign a new value to the specified slice """
''' Single value modification Index is 2 Is changed to 100 '''
lst = [10, 20, 30, 40]
lst[2] = 100
print(lst) # [10, 20, 100, 40]
''' Scope modification Index [1-3) Is changed to 200,300,400,500 '''
lst = [10, 20, 30, 40]
lst[1:3] = [200, 300, 400, 500]
print(lst) # [10, 200, 300, 400, 500, 40]

2.12 Sort

""" @author GroupiesM @date 2022/4/28 15:54 @introduction There are two common ways 1) call sort() Method , By default, all elements in the column are sorted in descending order , You can specify revers=True, Sort in descending order 2) Call built-in functions sorted(), You can specify revers=True, Sort in descending order difference : sort() Process the original list sorted() Return to a new list , The original list doesn't change """
''' 1) sort Sort Specify the parameters reverse=True You can sort in reverse Call list methods reverse Can be reversed to achieve reverse sort '''
'''1.1 Ascending sort '''
lst = [10, 90, 20, 80, 30, 70]
lst.sort()
print(lst) # [10, 20, 30, 70, 80, 90]
'''1.2 null '''
lst = [10, 90, 20, 80, 30, 70]
lst.sort(reverse=True) # reverse=True Represents a descending sort , Default reverse=False
print(lst) # [90, 80, 70, 30, 20, 10]
'''1.3 null '''
lst = [10, 90, 20, 80, 30, 70]
lst.sort()
lst.reverse()
print(lst) # [90, 80, 70, 30, 20, 10]
''' 2) sorted Sort '''
print("-------------")
'''2.1 Ascending sort '''
lst = [10, 90, 20, 80, 30, 70]
n_lst = sorted(lst)
print(n_lst) # [10, 20, 30, 70, 80, 90]
'''2.2 null '''
lst = [10, 90, 20, 80, 30, 70]
n_lst = sorted(lst, reverse=True)
print(n_lst) # [90, 80, 70, 30, 20, 10]

2.13 List generator

""" @author GroupiesM @date 2022/4/28 16:05 @introduction Full name " The formula for generating the list " Grammar format : [fx(i) for i in range(n,m)] fx(i): expression i : Custom variable range(n,m) : Iteratable object matters needing attention : In an expression that represents a list element , Usually contains custom variables """
lst = [i * i for i in range(0,10)]
print(lst) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
''' First cycle i=0, i*i = 0 The second cycle i=1, i*i = 1 The third cycle i=2, i*i = 4 The fourth cycle i=3, i*i = 9 Fifth cycle i=4, i*i = 16 '''

2.14 transformation -zip->list

""" @author GroupiesM @date 2022/6/22 15:22 @introduction Built in functions zip(): Used to take iteratable objects as parameters , Package the corresponding elements in the object into a tuple , Then return a list of these tuples key-value When the quantity is inconsistent , Refer to the short board effect """
items = [' Fruits ', ' Book ', ' Fish tank ', ' closestool ']
prices = [10, 20, 30]
zip = zip(items, prices)
lst = list(zip)
print(type(zip), zip) # <class 'zip'> <zip object at 0x1046d6e80>
print(type(lst), lst) # <class 'list'> [(' Fruits ', 10), (' Book ', 20), (' Fish tank ', 30)]

3、 ... and 、 aggregate set -> {k1,k2,…}

3.1 brief introduction & characteristic

characteristic
1) Is a variable sequence
2) Automatic weight removal
3) The elements in the collection are arranged out of order

""" @author GroupiesM @date 2022/4/28 17:14 @introduction <class 'set'> list :list = ['hello', 'world', 100] aggregate : set = {'python', 'hello', 90} Dictionaries :dict = {'name': ' Zhang San ', 'age': 100} Tuples :tuple = ('python','hello',90) character string : str = 'python' """
s = {
'python', 'hello', 90, 90}
print(type(s)) # <class 'set'>
print(s) # {90, 'python', 'hello'}

3.2 establish

""" @author GroupiesM @date 2022/4/29 15:21 @introduction Mode one : Use curly braces {}, Elements are separated by English commas set = {'python', 'hello', 90} Mode two : Built in functions list() Type conversion set(['hello','php']) # Tuples ->set set('hello') # character string ->set Set creation method : Mode one : Use curly braces {}, Elements are separated by English commas set = ['hello','python'] Mode two : Built in functions list() Type conversion set(('hello','php')) # list -> set set({'name': ' Zhang San ', 'age': 100}) # Dictionaries -> set set(['hello','php']) # Tuples -> set set({'python', 'hello', 90}) # aggregate -> set set('hello') # character string ->set """
''' Mode one '''
s = {
'hello', 'python'}
print(s) # {'python', 'hello'}
''' Mode two '''
'''1.list->set'''
set1 = set(('hello', 'php')) # list -> set
print('set1', set1) # {'php', 'hello'}
'''2. Dictionaries ->set when , Take the dictionary automatically key'''
set2 = set({
'name': ' Zhang San ', 'age': 100}) # Dictionaries -> set
print('set2', set2) # {'age', 'name'}
'''3. Tuples ->set'''
set3 = set(['hello', 'php']) # Tuples -> set
print('set3', set3) # {'php', 'hello'}
'''4. aggregate ->set'''
set4 = set({
'python', 'hello', 90}) # aggregate -> set
print('set4', set4) # {'python', 90, 'hello'}
'''5. character string ->set'''
set5 = set('hello') # character string ->set
print('set5', set5) # {'h', 'o', 'l', 'e'}

3.3 Judge in&not in

""" @author GroupiesM @date 2022/4/29 15:32 @introduction in、not in """
s = {
10, 20, 30, 40, 50}
print(10 in s) # True
print(100 in s) # False
print(15 not in s) # True

3.4 add to 2 Ways of planting

1. add(Object obj):set Set to add the specified element .

2. extend(Iterator iter): Ergodic sequence ( list 、 Tuples 、 Collection etc. ), Get the elements and add them to set aggregate .


3.4.1 add()- Add specified elements

""" @author GroupiesM @date 2022/6/28 11:06 @introduction add(Object obj): Add an element """
s = {
10, 20, 30, 40, 50}
s.add(60)
print(s) # {40, 10, 50, 20, 60, 30}

3.4.1 update()- Traverse iterable Adds the element to set

""" @author GroupiesM @date 2022/6/28 11:06 @introduction update(Iterator iter): Add an iterator ( list 、 Tuples 、 Collection etc. ) """
s = {
10, 20, 30, 40, 50}
s.update(['a', 'b', 'c'])
print(s) # {'a', 40, 10, 50, 20, 'c', 'b', 60, 30}

3.5 Delete 4 Ways of planting

1. remove(Object obj): Delete the specified Key The elements of .
1) Delete one element at a time .
2)Key If it doesn't exist, throw KeyError.

2. discard(Integer i): Delete the specified Key The elements of .
1)Key There is no non reporting error .

3. pop( ): Delete the leftmost element .( Pop up on the left )

4. clear(): Empty the set .


3.5.1 remove()- Delete the specified Key

""" @author GroupiesM @date 2022/6/22 17:14 @introduction remove(Object obj): Deletes the specified element , There is no such thing as throw KeyError """
s = {
10, 20, 30, 40, 50}
s.remove(10)
print(s) # {40, 50, 20, 30}

3.5.2 discard()- Delete the specified Key( There is no non reporting error )

""" @author GroupiesM @date 2022/6/22 17:15 @introduction discard(Object obj): Deletes the specified element , There is no non reporting error """
s = {
10, 20, 30, 40, 50}
s.discard(15)
s.discard(20)
print(s) # {40, 10, 50, 30}

3.5.3 pop()- Pop up on the left 1 individual

""" @author GroupiesM @date 2022/6/22 17:15 @introduction pop(): Delete an arbitrary element ( Pop up on the left ) """
s = {
10, 20, 30, 40, 50}
s.pop()
print(s) # {10, 50, 20, 30}

3.5.4 clear()- clear list

""" @author GroupiesM @date 2022/6/22 17:15 @introduction clear(): Empty """
s = {
10, 20, 30, 40, 50}
s.clear()
print(s) # set()

3.6 Judge - A collection of relations 4 Ways of planting

""" @author GroupiesM @date 2022/4/29 15:43 @introduction Set relation concept : 1. A subset of : If a A set is b A subset of a set , that a All elements in the collection , stay b All exist in the set , that a Namely b Subset , Write it down as "a∈b" 2. True subset : In the above case ,b At least one element in does not belong to a, that a Namely b The proper subset of , Write it down as "A⊊B" 3. Superset : If a yes b The proper subset of , that b Namely a Superset Judge the set relation 4 Ways of planting : 1. Is the element equal == or != 2. Is it a subset issubset() 3. Superset ( The definition of superset here is different from that in mathematics ,ab When the set elements are completely equal , They are also supersets of each other ) issuperset() 4. Whether there is no intersection isdisjoint() """

3.6.1 Judge the set relation -== or !=

""" @author GroupiesM @date 2022/6/22 17:19 @introduction 1. Is the element equal == or != """
a = {
1, 2}
a1 = {
1, 2}
b = {
1, 2, 3, 4, 5}
c = {
5, 6}
d = {
6, 7}
print('---------- Is the element equal ----------')
print(a == a1) # True
print(a != a1) # Fasle

3.6.2 Judge the set relation -issubset()

""" @author GroupiesM @date 2022/6/22 17:20 @introduction 2. Is it a subset issubset() """
a = {
1, 2}
a1 = {
1, 2}
b = {
1, 2, 3, 4, 5}
c = {
5, 6}
d = {
6, 7}
print('---------- Is it a subset issubset()----------')
print(a.issubset(a1)) # True
print(a.issubset(b)) # True
print(a.issubset(c)) # False

3.6.3 Judge the set relation -issuperset()

""" @author GroupiesM @date 2022/6/22 17:20 @introduction 3. Superset ( The definition of superset here is different from that in mathematics ,ab When the set elements are completely equal , They are also supersets of each other ) issuperset() """
a = {
1, 2}
a1 = {
1, 2}
b = {
1, 2, 3, 4, 5}
c = {
5, 6}
d = {
6, 7}
print('---------- Superset issuperset()----------')
print(a.issuperset(a1)) # True
print(b.issuperset(a)) # True
print(b.issuperset(c)) # False

3.6.4 Judge the set relation -isdisjoint()

""" @author GroupiesM @date 2022/6/22 17:20 @introduction 4. Whether there is no intersection isdisjoint() """
a = {
1, 2}
a1 = {
1, 2}
b = {
1, 2, 3, 4, 5}
c = {
5, 6}
d = {
6, 7}
print('---------- Whether there is no intersection isdisjoint()----------')
print(a.isdisjoint(a1)) # False
print(b.isdisjoint(c)) # False
print(b.isdisjoint(d)) # True

3.7 Mathematical calculation - aggregate

""" @author GroupiesM @date 2022/4/29 15:59 @introduction intersection : {1,2} & {2,3} => {2} Mode one :intersection() Mode two :& Combine : {1,2} & {2,3} => {1,2,3} Mode one :union() Mode two :| Difference set : {1,2} x {2,3} => {1} Mode one :difference() Mode two :- Symmetric difference set : {1,2} & {2,3} => {1,3} Mode one :symmetric_difference() Mode two :^ => shift + Numbers 6 """
s1 = {
1, 2}
s2 = {
2, 3}
print('--------- intersection {2} --------')
print(s1.intersection(s2))
print(s1 & s2)
print('--------- Combine {1, 2, 3}--------')
print(s1.union(s2))
print(s1 | s2)
print('--------- Difference set {1}--------')
print(s1.difference(s2))
print(s1 - s2)
print('--------- Symmetric difference set {1,3}--------')
print(s1.symmetric_difference(s2))
print(s1 ^ s2)

3.8 Set generative

""" @author GroupiesM @date 2022/4/29 16:06 @introduction <class 'set'> Full name " Formulas for generating sets " Grammar format : {fx(i) for i in range(n,m)} fx(i): expression i : Custom variable range(n,m) : Iteratable object matters needing attention : take {} Change it to [], Namely list List generator """
set1 = {
i * 2 for i in range(1, 5)}
print(set1) # {8, 2, 4, 6}

Four 、 Dictionaries dict -> {k1:v1,…}

4.1 brief introduction

""" @author GroupiesM @date 2022/4/28 16:09 @introduction <class 'dict'> list :list = ['hello', 'world', 100] Dictionaries :dict = {'name': ' Zhang San ', 'age': 100} Tuples :tuple = ('python','hello',90) aggregate : set = {'python', 'hello', 90} character string : str = 'python' Dictionaries :python One of the built-in data structures , Like a list, it's a variable sequence With 【 Key value pair 】 How to store data , A dictionary is an unordered sequence of numbers m1 = {'name': ' Zhang San ', 'age': 100} Realization principle : The implementation principle of the dictionary is similar to that of looking up the dictionary , Look up the dictionary to find the corresponding page number according to the radical or Pinyin Python The dictionary in is based on key lookup value Where it is id = hash(key) Dictionary view : See 4.8 There are three ways to get the dictionary view dict_keys: <class 'dict_keys'> dict_values: <class 'dict_values'> dict_items: <class 'dict_items'> """
dict = {
'name': ' Zhang San ', 'age': 100}
print(type(dict)) # <class 'dict'>
print(dict) # {'name': ' Zhang San ', 'age': 100}

4.2 establish

""" @author GroupiesM @date 2022/4/28 16:17 @introduction Dictionary creation method : Mode one : Use curly braces {}, Elements are separated by English commas scores = {'name': ' Zhang San ', 'age': 100} Mode two : Built in functions dict() Type conversion dict(k1=v1,k2=v2,...) """
''' Mode one '''
dct1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
print(dct1) # {'name': ' Zhang San ', 'age': 100, 'salary': 1888}
''' Mode two '''
dct2 = dict(name=' Zhang San ', age=100, salary=1888)
print(dct2) # {'name': ' Zhang San ', 'age': 100, 'salary': 1888}
''' An empty dictionary '''
dct3 = {
} # An empty dictionary 
print(dct3) # {}

4.3 characteristic

""" @author GroupiesM @date 2022/4/28 16:52 @introduction 1) All the elements are k-v Key value pair ,key No repetition ,value Can be repeated 2) The elements in the dictionary are out of order 3) In the dictionary key Must be a basic type ( Immutable object ) 4) Dictionaries can also be dynamically scaled as needed 5) Dictionaries waste a lot of memory , It is a data structure that uses space for time """
''' 1) All the elements are k-v Key value pair ,key No repetition ,value Can be repeated {'name': ' Li Si '} {'name': ' Zhang San ', 'nickname': ' Zhang San '} '''
m1 = {
'name':' Zhang San ','name':' Li Si '}
print(m1)
m1 = {
'name':' Zhang San ','nickname':' Zhang San '}
print(m1)

4.4 lookup k->v

""" @author GroupiesM @date 2022/4/28 16:26 @introduction m1 = {'name': ' Zhang San ', 'age': 100, 'salary': 1888} Mode one : []: give an example m1[' Zhang San '] Mode two : get(): give an example m1.get(' Zhang San ') difference : []: If there is no specified key, Throw out keyError abnormal get(): If there is no specified key, return None, You can set the default through parameters value, We can't find it key Returns the default value """
m1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
''' Mode one :[] obtain name'''
name = m1['name']
print(name) # Zhang San 
''' Mode two :get() obtain age'''
age = m1.get('age')
print(age) # 100
''' Mode two :get() Get what doesn't exist key'''
address = m1.get('address')
print(address) # None
''' Mode two :get() Get what doesn't exist key, And specify the default value '''
address = m1.get('address','china')
print(address) # china
''' Mode two :get() Get existing key, And specify the default value , The default value does not work '''
salary = m1.get('salary','1 ten thousand ')
print(salary) # 1888

4.5 Judge in&not in

""" @author GroupiesM @date 2022/4/28 16:34 @introduction key The judgment of the in: Appoint key There is a return in the dictionary True not in: Appoint key There is no return in the dictionary True """
m1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
b1 = 'name' in m1
b2 = 'address' in m1
b3 = 'country' not in m1
print(b1) # True
print(b2) # False
print(b3) # True

4.6 Additive elements -k=v

""" @author GroupiesM @date 2022/4/28 16:37 @introduction dict['key']= xxx """
m1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
m1['country'] = ' China '
print(m1) # {'name': ' Zhang San ', 'age': 100, 'salary': 1888, 'country': ' China '}

4.7 Remove elements -del

""" @author GroupiesM @date 2022/4/28 16:37 @introduction del dict['key'] """
m1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
del m1['salary']
print(m1) # {'name': ' Zhang San ', 'age': 100}

4.8 Get dictionary view 3 Ways of planting

""" @author GroupiesM @date 2022/4/28 16:40 @introduction The way 1:keys() : Get all in the dictionary key return type :<class 'dict_keys'> The way 2:values() : Get all in the dictionary value return type :<class 'dict_values'> The way 3:items() : Get all in the dictionary key,value Yes return type :<class 'dict_items'> """

4.8.1 Get all the information in the field key-keys()

""" @author GroupiesM @date 2022/6/22 14:51 @introduction <class 'dict_keys'> """
map = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
key_lst = map.keys()
print(key_lst, type(key_lst)) # dict_keys(['name', 'age', 'salary']) <class 'dict_keys'>
''' dict_keys -> list among dict_keys It's a tuple type (), See b1 Tuples tuple '''
print(list(key_lst)) # ['name', 'age', 'salary']

4.8.2 Get all in the dictionary value-values()

""" @author GroupiesM @date 2022/6/22 14:51 @introduction <class 'dict_values'> """
map = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
value_lst = map.values()
print(value_lst, type(value_lst)) # dict_values([' Zhang San ', 100, 1888]) <class 'dict_values'>
''' dict_keys -> list among dict_keys It's a tuple type (), See b1 Tuples tuple '''
print(list(value_lst)) # [' Zhang San ', 100, 1888]

4.8.3 Get all in the dictionary kv Yes -items()

""" @author GroupiesM @date 2022/6/22 14:52 @introduction <class 'dict_items'> """
map = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
item_lst = map.items()
print(item_lst, type(item_lst)) # dict_items([('name', ' Zhang San '), ('age', 100), ('salary', 1888)]) <class 'dict_items'>
''' dict_keys -> list among dict_keys It's a tuple type (), See b1 Tuples tuple '''
print(list(item_lst)) # [('name', ' Zhang San '), ('age', 100), ('salary', 1888)]

4.9 Traverse

""" @author GroupiesM @date 2022/4/28 16:49 @introduction i yes dict All of the key adopt dict.get(i)、 or dict[i] For each key Corresponding value for i in dict: print(i,dict.get(i)) for i in dict: print(i,dict[i]) """
''' Traverse key-value name Zhang San age 100 salary 1888 '''
m1 = {
'name': ' Zhang San ', 'age': 100, 'salary': 1888}
for k in m1:
print(k, m1.get(k))
''' Traverse value Zhang San 100 1888 '''
for v in m1.values():
print(v,end="\t")

4.10 transformation -zip->dict

""" @author GroupiesM @date 2022/6/22 15:22 @introduction Grammar format : {k: v for k, v in zip} k : Custom variable key v : Custom variable value zip : Can the iteration zip object Built in functions zip(): Used to take iteratable objects as parameters , Package the corresponding elements in the object into a tuple , Then return a list of these tuples key-value When the quantity is inconsistent , Refer to the short board effect """
items = [' Fruits ', ' Book ', ' Fish tank ', ' closestool ']
prices = [10, 20, 30]
''' Mode one :dict()'''
zip1 = zip(items, prices)
dct1 = dict(zip1)
print(type(zip1), zip1) # <class 'zip'> <zip object at 0x1046d6e80>
print(type(dct1), dct1) # <class 'dict'> {' Fruits ': 10, ' Book ': 20, ' Fish tank ': 30}
''' Mode two :{k: v for k, v in zip}'''
zip2 = zip(items, prices)
dct2 = {
k: v for k, v in zip2} # zip1 Can only be used once , If you continue to use here zip1, Returns an empty dictionary dct2
print(type(dct2), dct2) # <class 'dict'> {' Fruits ': 10, ' Book ': 20, ' Fish tank ': 30}

22/06/28

M


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