05 Python – list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

Time:2021-4-3

Data structures are basically – they’re structures that can handle some data. In other words, they are used to store a set of related data.

There are four built-in data structures in Python — lists, tuples and dictionaries, and collections. We will learn how to use them and how they make programming easy

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

1、 List

It’s a data structure that processes a set of ordered items, that is, you can store a sequence of items in a list. Imagine that you have a shopping list that records what you want to buy, so you can easily understand the list. It’s just that everything may be on its own line on your shopping list,

In Python, you separate each project with a comma. The items in the list should be included in square brackets so Python knows that you are indicating a list.

Once you create a list, you can add, delete, or search for items in the list.Since you can add or delete items, we say that a list is a variable data type, which can be changed

#Shopping list
Shoplist = ['apple ',' mango ',' carrot ',' Banana ']

basic operation

Print ('I have ', len (shoplist),' items in my shopping list. '
Print ('They are: '), # prompt
​
for item in shoplist:
    print(item)
I also bought rice
​
shoplist.append ('rice ')
Print ('Now my shopping list is', shoplist)
#['apple ',' mango ',' carrot ',' Banana ',' rice ']

Basic operation – add

Append

Li = ['apple ',' mango ',' carrot ',' Banana ']
li.append ('rice ')
print(li)
#['apple ',' mango ',' carrot ',' Banana ',' rice ']
​
li.append(1)
#['apple ',' mango ',' carrot ',' Banana ',' rice ', 1]
​
print(li.append('hello'))   
#None: no return value, li.append () it's just a method, an action
​
print(li)   
#['apple ',' mango ',' carrot ',' Banana ',' rice ', 1,' hello ']

insert insert

Li = ['apple ',' mango ',' carrot ',' Banana ']
li.insert (3,'strawberry ')
​
print(li)   
#['apple ',' mango ',' carrot ',' Strawberry ',' Banana ']

extend Append to end

Li = ['apple ',' mango ',' carrot ',' Banana ']
li.extend('cc')
print(li)
#['apple ',' mango ',' carrot ',' Banana ',' C ',' C ']
​
li.extend([1,2,3])
print(li)
#['apple ',' mango ',' carrot ',' Banana ',' C ',' C ', 123]
​
li.extend (123) # error: the number cannot be iterated
print(li)   
#TypeError: 'int' object is not iterable

Application example:

Enter employee name continuously, enter Q / Q to exit and print the list

li = []
while True:
    User name = input ("please enter the name of the employee to be added):)
    if username.strip().upper() == 'Q':
        break
    li.append(username)
    print(li)
print(li)

Results of operation:

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection]

List – delete

remove: delete by element

Li = ['apple ',' mango ',' carrot ',' Banana ']
li.remove ('mango ')
print(li)  
#['apple ',' carrot ',' Banana ']

pop: delete by index – return value

Li = ['apple ',' mango ',' carrot ',' Banana ']
name =  li.pop (1) With return value
print(name,li)
#Mango ['apple ',' carrot ',' Banana ']
​
name =  li.pop () if the index is not written, the last one will be deleted by default
print(name,li)
#Banana ['apple ','carrot']

clear: empty

Li = ['apple ',' mango ',' carrot ',' Banana ']
li.clear()
print(li)
#[]

del: delete

Li = ['apple ',' mango ',' carrot ',' Banana ']
del li[2:]
print(li)
#['apple ','mango']
​
After del Li # is deleted, it no longer exists and an error is printed
print(li)
 #NameError: name 'li' is not defined

Circular deletion

li = [11,22,33,44,55]
for i in range(len(li)):
    print(i)
    del li[0]
    print(li)

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

List – change

[index]=”Revised content”

Li = ['apple ',' mango ',' carrot ',' Banana ']
Li [0] ='pitaya '#
print(li)
#['pitaya ',' mango ',' carrot ',' Banana ']

[slice]=”Modified content” (iterative: divided into the smallest elements and added one by one)

Li = ['apple ',' mango ',' carrot ',' Banana ']
li[0:2] = 'abcd' 
#Replace index 0-2 with ABCD, slice and iterate
​
print(li)
//['a ',' B ',' C ','d', 'carrot', 'Banana']
​
Li [0:3] = ['I ',' like ',' eat ',' fruit ']
print(li)
//['I ',' like ',' eat ',' fruit ','d', 'carrot', 'Banana'

List – check

From beginning to end: for loop

Li = ['apple ',' mango ',' carrot ',' Banana ']
for i in li:
    print(i)

One: index

Li = ['apple ',' mango ',' carrot ',' Banana ']
Print (Li [1]) mango

Section one: slicing

Li = ['apple ',' mango ',' carrot ',' Banana ']
Print (Li [0:2]) # ['apple ',' mango ',' carrot ']

List nesting

Li = ['apple ',' mango ',' carrot ',' a ',' B ',' C '],'banana']
Print (Li [2] [1])
li[3][0].upper() 
#Capitalizes the first element of the fourth element list
​
print(li)
#['apple ',' mango ',' carrot ',' a ',' B ',' C '],'banana']

List – circular printing

#The index starts from zero by default
li = ['alex','taibai','wusir','egon']
for i in li:
    print(li.index(i),i)
The specified index starts at 100
Results of operation:

Other common operations

split:String to list STR — > List

s = 'xcsd_ cdc_ eht_ 'mumu '
print(s.split('_'))  
//['xcsd ','cdc','eht ','mumu']
​
S1 ='xc SDC DC eht Zengmu '
print(s1.split(' '))    
//['xc ','sdc','dc ','eht','mumu ']

join:List to string list — > str

Join (iteratable) split

Iteratable objects: list, STR, Yuanzu

Li = ['xcsd ',' CDC ',' eht ',' Mumu ']
s = ''.join(li)
Print (s) # xcsdcheht wood
s1 = '_'.join(li)
print(s1)  #xcsd_ cdc_ eht_ Wood

range: look at the head and ignore the tail — equivalent to an orderly list of numbers (can be reversed, plus step size)

for i in range(2,6):
    print(i)

Application example:

Circulation printing, the list encountered in the list also need circulation printing

li = [1,2,3,5,'alex',[2,3,4,5,'taibai'],'afds']
for i in li:
    if type(i) == list:
        for n in i:
            print(n)
    else:
        print(i)

Results of operation:

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

2、 Yuanzu

Tuples are very similar to lists, except that tuples are immutable like strings, that is, you can’t modify tuples. Tuples are defined by comma separated items in parentheses.

Tuples are usually used when a statement or user-defined function can safely adopt a set of values, that is, the value of the used tuple will not change

tu1 = (1)
tu2 = (1,)
print(tu1,type(tu1))    #1 <class 'int'>
print(tu2,type(tu2))    #(1,) <class 'tuple'>
tu3 = ([1])
tu4 = ([1],)
print(tu3,type(tu3))    #[1] <class 'list'>
print(tu4,type(tu4))    #([1],) <class 'tuple'>

Basic operations of tuples

tu = (1,2,3,'alex','egon')
print(tu[2])    #3
print(tu[0:2])  #(1, 2)
for i in tu:
    Print (I) # circular printing

Dictionaries

A dictionary is similar to an address book where you look up addresses and contact details by contact name, that is, we associate keys (names) with values (details). Note that the key must be unique, just like if there are two people with the same name, you can’t find the right information.

Note that you can only use immutable objects (such as strings) as dictionary keys, but you can use immutable or mutable objects as dictionary values.

Basically, you should only use simple objects as keys.

Key value pairs are marked in the dictionary in this way:d = {key1 : value1, key2 : value2 }。

Note that their key / value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly braces

dict
The key must be an immutable data type and can be hashed
Value any data type

Dict advantage: binary search to query
Store a lot of relational data
Features: < = 3.5 version is out of order, after 3.6 is in order

1. Dictionary – add

DIC [‘key ‘] = value

dic1 = {'age':18,'name':'xc','sex':'female'}
dic1['height'] = 165
print(dic1) 
#No key value pair, increase
# {'age': 18, 'name': 'xc', 'sex': 'female', 'height': 165}
​
dic1['age'] = 21
print(dic1) 
#If there is a key value pair, modify it
#{'age': 21, 'name': 'xc', 'sex': 'female', 'height': 165}

SetDefault sets the default

# dic1 = {'age':18,'name':'xc','sex':'female'}
dic1.setdefault('weight',120)
print(dic1)     
#No key value pair, increase
# {'age': 18, 'name': 'xc', 'sex': 'female', 'weight': 120}
​
dic1.setdefault('name','aa')
print(dic1)      
#There are key value pairs, do not do any operation
# {'age': 18, 'name': 'xc', 'sex': 'female', 'weight': 120}

2. Dictionary – delete

Pop (with return value, no error will be reported when the content to be deleted does not exist) is preferred to del

Pop delete

dic1 = {'age':18,'name':'xc','sex':'female'}
print(dic1.pop('age'))  
#Delete directly with age --- with return value, press the key to delete
​
print(dic1)     
#18   {'name': 'xc', 'sex': 'female'}
​
Print (dic1. Pop ('erge ','No key / none')) 
 #No Erge --- return value can be set: no this key / none
print(dic1)

Randomly delete popitem

dic1 = {'age':18,'name':'xc','sex':'female'}
print(dic1.popitem())  
#('sex', 'female')
#Random delete: return value ----- return ancestor: delete key value

Clear clear

dic1 = {'age':18,'name':'xc','sex':'female'}
Dic1. Clear() # clear dictionary
print(dic1)     #{}

Del delete

dic1 = {'age':18,'name':'xc','sex':'female'}
del dic1['name']   
#If yes, delete it
#If del dic1 ['name1 '] ා no, an error is reported
​
print(dic1)     
#{'age': 18, 'sex': 'female'}

3. Dictionary

update

dic = {'age':18,'name':'xc','sex':'female'}
dic2 = {'name':'alex','weight':'168'}
dic2.update(dic)      
#If there is, the coverage will be updated; if there is no, the coverage will be increased
​
print(dic)  
#{'age': 18, 'name': 'xc', 'sex': 'female'}
​
print(dic2) 
#{'name': 'xc', 'weight': '168', 'age': 18, 'sex': 'female'}

4. Dictionary search

keys,values,items

dic1 = {'age':18,'name':'xc','sex':'female'}
​
print(dic1.keys(),type(dic1.keys()))    
#Key Dict_ keys(['age', 'name', 'sex']) <class 'dict_ keys'>
​
print(dic1.values())    
#Value Dict_ values([18, 'xc', 'female'])
​
print(dic1.items())     
#Dict_ items([('age', 18), ('name', 'xc'), ('sex', 'female')])

Get the key value, first get

Print (dic1 ['name '])
#Print (dic1 ['name1 ']) #
​
print(dic1.get('name'))  
#With name output directly --- with return value
​
Print (dic1. Get ('name1 ','No key'))  
#No name1 --- return value can be set: no this key / none

Cyclic output

for i in dic1:
    Print (I) # cycle print key (default is key)
for i in dic1.keys():
Print (I) # cycle print key
for i in dic1.values():
Print (I) # cycle print value

5. Nesting of dictionaries

dic = {    'name':['alex','wusir','xinchen'],
    'py9':{
        'time':'1213',
        'study_fee':19800,
        'addr':'CBD',
    },
    'age':21
}
dic['age'] = 56 
#Find age and update to 56
print(dic)
​
dic['name'].append('rt')    
#Find the name and add it
print(dic)
​
dic['name'][1] = dic['name'][1].upper() 
#Find name and capitalize wusir
print(dic)
​
dic['py9']['female'] = 6    
#Find Yuanzu and add key value pairs female:6
print(dic)

Application example:

#Input a string of characters, encounter letters, convert to '﹤ u' , and print out

Info = input ('Please input: ')
for i in info:
    if i.isalpha():
        info = info.replace(i,'_')
print(info)

Results of operation:

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

4、 Set

A collection is like a list, but each element must be unique and immutable:

It’s disordered

basic operation

print(set1)     
#{1, 2, 3}
​
set2 = {1,2,3,[2,3],{'name':'xc'}}  
#The list is mutable (not hashable), so there was an error
print(set2)     
#TypeError: unhashable type: 'list'

1. Set — increase

add

set1 = {'alex','wusir','ritian','egon','barry'}
#(1) add # because the set is unordered, the result of each run is not necessarily the same, and the added position is not necessarily the same
set1.add('nvshen')  
#{'ritian', 'nvshen', 'egon', 'wusir', 'alex', 'barry'}
print(set1)

update

set1.update('xc')   
#Iterative addition is still out of order
print(set1) 
#{'egon', 'x', 'wusir', 'nvshen', 'c', 'alex', 'ritian', 'barry'}

2. Set – delete

set1 = {'alex','wusir','ritian','egon','barry'}

pop–Random deletion

print(set1.pop())   
#Egon: with return value, return the content deleted this time
​
print(set1)     
#{'barry', 'alex', 'wusir', 'ritian'}

remove——Specified element deletion

set1.remove('alex')
print(set1)    
 #{'egon', 'wusir', 'barry', 'ritian'}

clear——Empty

set1.clear()
print(set1)     
#Empty set: set ()

del

del set1        
​
#After deleting, the collection does not exist and an error is reported
print(set1)    
 #NameError: name 'set1' is not defined

3. The set cannot be changed

Set is out of order;

The elements in the collection are immutable data types

4. Assemble – check

set1 = {'alex','wusir','ritian','egon','barry'}
for i in set1:
    print(i)

Results of operation:

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

5. Operations between sets

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}

intersection

print(set1 & set2)      
#(1) {4, 5}
​
print(set1.intersection(set2))      
#(2) {4, 5}

Union

print(set1 | set2)          
#(1) {1, 2, 3, 4, 5, 6, 7, 8}
​
print(set1.union(set2))     
#(2) {1, 2, 3, 4, 5, 6, 7, 8}

Anti intersection–Elements other than intersection

print(set1 ^ set2)          
#(1) {1, 2, 3, 6, 7, 8}
​
print(set1.symmetric_difference(set2))     
#(2) {1, 2, 3, 6, 7, 8}

Difference set–The former is unique

print(set1 - set2)              #(1) {1, 2, 3}
print(set1.difference(set2))     #(2) {1, 2, 3}
print(set2 - set1)              #(1) {8, 6, 7}
print(set2.difference(set1))     #(2) {8, 6, 7}

Subsets and supersets

set3 = {1,2,3,4,5}
set4 = {1,2,3,4,5,6,7,8}
Print ('--- set3 is a subset of SET4 ---)
print(set3 < set4)      #True
print(set3.issubset(set4))   #True
​
Print ('--- SET4 is a superset of set3 ---)
print(set4 > set3)      #True
print(set4.issuperset(set3))   #True

5、 Public method

sort

Forward sort: sort ()

li = [1,5,4,2,6,7,3]
li.sort()
print(li)   #[1, 2, 3, 4, 5, 6, 7]

Reverse order: li.sort (reverse = True)

li = [1,5,4,2,6,7,3]
li.sort(reverse = True)
print(li)   #[7, 6, 5, 4, 3, 2, 1]

reversal: li.reverse ()

li = [1,5,4,2,6,7,3]
li.reverse()
print(li)     #[3, 7, 6, 2, 4, 5, 1]

Supplement:

String list sort — sort according to the ASCII code corresponding to the first character of the string

li = ['ojhy','asa','cvd','hdk']
li.sort()
print(li)   #['asa', 'cvd', 'hdk', 'ojhy']

Count () counts the number of times the element appears

Li = ['xcsd ','cdc','mumu ', [1, 5, 2],'eht','mumu ']
num =  li.count ('mu Mu ')
​
Print (Num) # 2: 'Mumu' appears twice

Len() calculates the length of the list

Li = ['xcsd ','cdc','mumu ', [1, 5, 2],'eht','mumu ']
l = len(li)
Print (L) # 6: the list length is 6

li.index (‘element ‘) view index

Li = ['xcsd ','cdc','xinchen ', [1, 5, 2],'eht','xinchen ']
print(li.index('eht'))  
#4: The index of 'eht' is 4

6、 Differences and similarities and differences

List Tuple Set Dictionary Dict
Can I read and write Reading and writing read-only Reading and writing Reading and writing
Can it be repeated yes yes no yes
Storage mode value value Key < br / > (cannot be repeated) Key value pair < br / > (key cannot be repeated)
Is it orderly Order Order disorder Automatic positive sequence
initialization [1,’a’] (‘a’, 1) Set ([1,2]) < br / > or {1,2} {‘a’:1,’b’:2}
add to append read-only add d[‘key’] = ‘value’
Reading elements l[2:] t[0] nothing d[‘a’]

05 Python - list, Yuanzu, dictionary, set operation Encyclopedia: recommended collection

Practice address:www.520mg.com/it