Python-a complete collection of list, primitive, dictionary, and set operations: recommended collection

In-depth article: 5861 words | 10 minutes to read

Data structures are basically just that – they are 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 sets. We’ll learn how to use them and how they make programming easy

1. List list

Is a data structure that handles an ordered set of items, i.e. you can store a sequence of items in a list. Imagine you have a shopping list of things you want to buy. It will be easier for you to understand the list. It’s just that on your shopping list, everything may have its own row.

In Python, you separate each item with a comma. The items in the list should be enclosed in square brackets so that Python knows you are specifying a list.

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

# Shopping list
shoplist = ['Apple', 'Mango', 'Carrot', 'Banana']

Basic operations

print ('I have', len(shoplist),' items in my shopping list.')
print ('They are:'), # prompt

for item in shoplist:
    print(item)
print ('I also bought rice.')

shoplist.append('rice')
print ('Now my shopping list is', shoplist)
# ['Apple', 'Mango', 'Carrot', 'Banana', 'Rice']

Basic operation – add

append 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() is just a method and 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 the 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: Numbers cannot be iterated
print(li)
#TypeError: 'int' object is not iterable

Application examples:

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

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

operation result:

List – Delete

remove: Remove by element

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

pop: delete according to index – return value

li = ['apple', 'mango', 'carrot', 'banana']
name = li.pop(1) #has return value
print(name,li)
# Mango ['apple', 'carrot', 'banana']

name = li.pop() #If no index is written, the last one will be deleted by default
print(name,li)
# Banana ['Apple', 'Carrot']

clear: Clear

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

del: Delete

li = ['apple', 'mango', 'carrot', 'banana']
delli[2:]
print(li)
# ['Apple', 'Mango']

del li # After deletion, it no longer exists and an error will be printed.
print(li)
 #NameError: name 'li' is not defined

Cycle deletion

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

List – Change

li[index] = modified content’

li = ['apple', 'mango', 'carrot', 'banana']
li[0] = 'Dragon Fruit' #Change the position with index 0 to 'Dragon Fruit'
print(li)
# ['Dragon fruit', 'Mango', 'Carrot', 'Banana']

li[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 and process iteratively after slicing

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)

a certain one: index

li = ['apple', 'mango', 'carrot', 'banana']
print(li[1]) #Mango

segment: slice

li = ['apple', 'mango', 'carrot', 'banana']
print(li[0:2]) #['Apple', 'Mango', 'Carrot']

List – Nested

li = ['apple', 'mango', 'carrot', ['a','b','c'],'banana']
print(li[2][1]) #罗
li[3][0].upper()
#Change the first element of the fourth element in the list to uppercase

print(li)
# ['apple', 'mango', 'carrot', ['a', 'b', 'c'], 'banana']

List – Loop printing

#Index starts from zero by default

li = ['alex','taibai','wusir','egon']
for i in li:
    print(li.index(i),i)

#Specify index starting from 100

for index,i in enumerate(li,100):
    print(index,i)

operation result:

Other common operations

split: Convert string to list str->list

s = 'xcsd_cdc_eht_木木'
print(s.split('_'))
// ['xcsd', 'cdc', 'eht', 'Mumu']

s1 = 'xc sdc dc ehtzeng mumu'
print(s1.split(' '))
// ['xc', 'sdc', 'dc', 'ehtzeng', 'Mumu']

join: Convert list to string list->str

join(iterable object iterable) split

Iterable object iterable: list, str, ancestor

li = ['xcsd', 'cdc', 'eht', 'Mumu']
s = ''.join(li)
print(s) #xcsdcdceht木木
s1 = '_'.join(li)
print(s1) #xcsd_cdc_eht_木木

range: Pay attention to the beginning and not the end – equivalent to an ordered list of numbers (can be reversed and add steps)

for i in range(2,6):
    print(i)
    
for i in range(3): #Start from 0, 0 can be omitted

Application examples:

Loop printing, if you encounter a list in the list, you also need to loop 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)

operation result:

2. Yuanzu

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

Tuples are often used to enable statements or user-defined functions to safely take 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 on tuples

tu = (1,2,3,'alex','egon')
print(tu[2]) #3
print(tu[0:2]) #(1, 2)
for i in tu:
    print(i) #Loop to print the ancestor

Dictionary

A dictionary is similar to an address book where you look up addresses and contact details by name, i.e. we associate keys (names) with values (details). Note that the key must be unique, as you won’t be able to find the correct information if two people happen to have the same name.

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 this way:d = {key1 : value1, key2 : value2 }.

Note that their key/value pairs are separated by colons, and individual pairs are separated by commas, all enclosed in curly braces

dict
key must be an immutable data type, hashable
value (value) any data type

Advantages of dict: binary search to query
Store large amounts of relational data
Features: <=3.5 versions are out of order, and after 3.6 they are all in order

1. Dictionary – Add

dic[key’] = value

dic1 = {<!-- -->'age':18,'name':'xc','sex':'female'}
dic1['height'] = 165
print(dic1)
# If there is no key-value pair, add
# {'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 default

# dic1 = {'age':18,'name':'xc','sex':'female'}
dic1.setdefault('weight',120)
print(dic1)
# If there is no key-value pair, add
# {'age': 18, 'name': 'xc', 'sex': 'female', 'weight': 120}

dic1.setdefault('name','aa')
print(dic1)
#There are key-value pairs, no operation is performed
# {'age': 18, 'name': 'xc', 'sex': 'female', 'weight': 120}

2. Dictionary–Delete

To delete, use pop (which has a return value and does not report an error when the content to be deleted does not exist) instead of del.

pop delete

#
dic1 = {<!-- -->'age':18,'name':'xc','sex':'female'}
print(dic1.pop('age'))
#Delete directly if there is age---if there is a return value, press the key to delete

print(dic1)
#18 {'name': 'xc', 'sex': 'female'}

print(dic1.pop('erge','No such key/None'))
 #No erge----The return value can be set: no such key/None
 
print(dic1)
#No such key/None {'name': 'xc', 'sex': 'female'}

popitem randomly deleted

dic1 = {<!-- -->'age':18,'name':'xc','sex':'female'}
print(dic1.popitem())
#('sex', 'female')
#Random deletion: There is a return value-----Return to the ancestor: the deleted 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
# del dic1['name1'] #If not, an error will be reported

print(dic1)
#{'age': 18, 'sex': 'female'}

3. Dictionary–Change

update

dic = {<!-- -->'age':18,'name':'xc','sex':'female'}
dic2 = {<!-- -->'name':'alex','weight':'168'}
dic2.update(dic)
#If there is, update the coverage, if not, add it.

print(dic)
#{'age': 18, 'name': 'xc', 'sex': 'female'}

print(dic2)
#{'name': 'xc', 'weight': '168', 'age': 18, 'sex': 'female'}

4. Dictionary – Lookup

keys, values, items

dic1 = {<!-- -->'age':18,'name':'xc','sex':'female'}

print(dic1.keys(),type(dic1.keys()))
#Keys 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, get is preferred

print(dic1['name']) #If any, print
#print(dic1['name1']) #If not, an error will be reported

print(dic1.get('name'))
#With name, output directly---with return value

print(dic1.get('name1','No such key'))
#No name1----The return value can be set: there is no such key/None

Loop output

for i in dic1:
    print(i) #Loop print keys (default is key)
    
for i in dic1.keys():
    print(i) #Loop printing keys
    
for i in dic1.values():
    print(i) #loop print values
    
for i in dic1.items():
    print(i) #Loop to print key-value pairs

for k,v in dic1.items():
    print(k,v) #Print key and 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 it to 56
print(dic)

dic['name'].append('rt')
#Find the name and add the name
print(dic)

dic['name'][1] = dic['name'][1].upper()
#Find the name and change wusir to uppercase
print(dic)

dic['py9']['female'] = 6
#Find the ancestor and add the key-value pair female:6
print(dic)

Application examples:

#Input a string of characters, convert them to _’ when encountering letters, and print the output

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

operation result:

4. Gathering

Sets are similar to lists, but each element must be unique and immutable:

it is disordered

print(set1)
#{1, 2, 3}

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

Basic operations

1. Collection – Add

add

set1 = {<!-- -->'alex','wusir','ritian','egon','barry'}
# (1)add #Because the collection is unordered, the results may not be the same each time, and the added positions may not be the same either.
set1.add('nvshen')
#{'ritian', 'nvshen', 'egon', 'wusir', 'alex', 'barry'}
print(set1)

update

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

2. Collection – Delete

set1 = {<!-- -->'alex','wusir','ritian','egon','barry'}

pop – Random deletion

print(set1.pop())
#egon: There is a return value, returning the deleted content this time

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

remove–Delete the specified element

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

clear–clear

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

del

del set1

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

3. The collection cannot be changed

Sets are unordered;

The elements in the collection are immutable data types

4. Collection – Check

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

operation result:

5. Operations between collections

set1 = {<!-- -->1,2,3,4,5}
set2 = {<!-- -->4,5,6,7,8}

Intersection

print(set1 & amp; 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 – unique to the former

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 methods

Sort

Forward sorting: sort()

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

Sort in 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]

Reverse: li.reverse()

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

Additional:

String list sorting – sorting 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 an element appears

li = ['xcsd', 'cdc', 'Mumu',[1, 5, 2], 'eht', 'Mumu']
num = li.count('MUMU')

print(num) #2: 'Mumu' appears 2 times

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:'eht' has an index of 4

6. Differences and similarities

List list Tuple tuple Set Dictionary dict
Can I read and write Read and write Read only Read and write Read and write
Can it be repeated Yes Yes No Yes
Storage method value value

key

(cannot be repeated)

key value pair

(keys cannot be repeated)

Whether it is in order Ordered Ordered Unordered Auto-ordered
Initialization [1,’a’] (‘a’, 1)

set([1,2])
or {1,2}

{‘a’:1,’b’:2}
Add append Read only add d[‘key’] = ‘value’
Read element l[2:] t[0] None d[‘a’]

Finally:

I have prepared some very systematic Python materials. In addition to providing you with a clear and painless learning path, I have also selected the most practical learning resources and a huge library of mainstream crawler cases< /strong>. After a short period of study, you will be able to master the crawler skill well and obtain the data you want. Friends who need it can scan the QR code at the end of the article to obtain it.

01 is specially designed for 0 basic settings, and even beginners can learn it easily

We have interspersed all the knowledge points of Python into the comics.

In the Python mini-class, you can learn knowledge points through comics, and difficult professional knowledge becomes interesting and easy to understand in an instant.

Just like the protagonist of the comic, you travel through the plot, pass the levels, and complete the learning of knowledge unknowingly.

02 No need to download the installation package yourself, detailed installation tutorials are provided

03 Plan detailed learning routes and provide learning videos

04 Provide practical information to better consolidate knowledge

05 Provide interview information and side job information to facilitate better employment


This complete version of Python learning materials has been uploaded to CSDN. If you need it, you can scan the official QR code of csdn below or click on the WeChat card under the homepage and article to get the method. [Guaranteed 100% free]

syntaxbug.com © 2021 All Rights Reserved.