author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/83
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
Python There are a large number of data structures and containers for programming , In this section, we summarize the previous knowledge points , And expand some new knowledge , To introduce Python data structure .
Python The list in is variable , This is the most important feature that distinguishes it from strings and tuples , In a word, it is : The list can be modified , And strings and tuples cannot .
About Python For the details of the list, please refer to the preface Python List and Application
Here are Python Methods in the list :
The following example demonstrates most of the methods of listing ( On-line python3 Environmental Science ):
a = [2, 123, 123, 1, 1234.5]
print('''a.count(123), a.count(1), a.count('x')''')
print(a.count(123), a.count(1), a.count('x'), "\n")
a.insert(2, -1)
print('''a.insert(2, -1)''')
print(a, "\n")
a.append(456)
print('''a.append(456)''')
print(a, "\n")
a.index(456)
print('''a.index(456)''')
print(a.index(456), "\n")
a.remove(456)
print('''a.remove(456)''')
print(a, "\n")
a.reverse()
print('''a.reverse()''')
print(a, "\n")
a.sort()
print('''a.sort()''')
print(a, "\n")
Running results
a.count(123), a.count(1), a.count('x')
2 1 0
a.insert(2, -1)
[2, 123, -1, 123, 1, 1234.5]
a.append(456)
[2, 123, -1, 123, 1, 1234.5, 456]
a.index(456)
6
a.remove(456)
[2, 123, -1, 123, 1, 1234.5]
a.reverse()
[1234.5, 1, 123, -1, 123, 2]
a.sort()
[-1, 1, 2, 123, 123, 1234.5]
Be careful : similar insert, remove or sort The method of modifying the list has no return value .
The list method makes it easy to use the list as a stack , Stack as a specific data structure , The first element to enter is the last one to be released ( Last in, first out ). use append() Method can add an element to the top of the stack . With no index specified pop() Method can release an element from the top of the stack .
Refer to the following code ( On-line python3 Environmental Science ):
stack = ['Baidu', 'ShowMeAI', 'google']
stack.append('ByteDance')
stack.append('Tencent')
print(stack)
stack.pop()
print('''stack.pop()''')
print(stack, "\n")
stack.pop()
print('''stack.pop()''')
print(stack, "\n")
stack.pop()
print('''stack.pop()''')
print(stack, "\n")
The running result is
['Baidu', 'ShowMeAI', 'google', 'ByteDance', 'Tencent']
stack.pop()
['Baidu', 'ShowMeAI', 'google', 'ByteDance']
stack.pop()
['Baidu', 'ShowMeAI', 'google']
stack.pop()
['Baidu', 'ShowMeAI']
You can also use the list as a queue , Just the first element in the queue , The first to take it out ; But it's not efficient to use lists for such purposes . It's faster to add or pop up elements at the end of the list , However, it's not fast to insert in the list or pop it out of the head ( Because all the other elements have to move one by one ).
from collections import deque
queue = deque(['Baidu', 'ShowMeAI', 'google'])
queue.append('ByteDance')
queue.append('Tencent')
print(deque)
print('''queue.popleft()''')
print(queue.popleft(), "\n")
print('''queue.popleft()''')
print(queue.popleft(), "\n")
print(deque)
The running result is
<class 'collections.deque'>
queue.popleft()
Baidu
queue.popleft()
ShowMeAI
<class 'collections.deque'>
List derivation provides a simple way to create a list from a sequence . Usually an application applies some operations to each element of a sequence , Use the result as an element to generate a new list , Or create subsequences according to certain criteria .
Every list derivation is in for Followed by an expression , Then there are zero to many for or if Clause . The return result is based on the expression from the following for and if The list generated in the context . If you want the expression to derive a tuple , You have to use brackets .
vec = [1, 2, 3]
# Multiply each value in the list by three , Get a new list :
three_times_vec = [3*x for x in vec]
print(three_times_vec)
# Square each value in the list , And form a list with the original values, and then form a new list :
cmp_x_square = [[x, x**2] for x in vec]
print(cmp_x_square)
Running results
[3, 6, 9]
[[1, 1], [2, 4], [3, 9]]
List derivation can also be used to call a certain function method for each element in the sequence :
fruits = ['banana', 'loganberry', 'apple']
print([fruit.upper() for fruit in fruits])
# Output ['BANANA', 'LOGANBERRY', 'APPLE']
In the list derivation, you can use if Clause to build a filter to filter the generated results :
[3*x for x in vec if x > 2]
# result [9]
[3*x for x in vec if x < 3]
# result [3, 6]
You can also combine two lists to build more complex results using list derivation
vec1 = [1, 2, 3]
vec2 = [4, 5, 6]
[x*y for x in vec1 for y in vec2] # Multiply by two to get a new list
# result [4, 5, 6, 8, 10, 12, 12, 15, 18]
[x+y for x in vec1 for y in vec2] # Add two to get a new list
# result [5, 6, 7, 6, 7, 8, 7, 8, 9]
[vec1[i]*vec2[i] for i in range(len(vec1))] # Multiply the corresponding positions to get a new list
# result [4, 10, 18]
Python Lists can also be nested .
The following code shows 3X4 Matrix list of ( On-line python3 Environmental Science ):
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
# take 3X4 The matrix list of is converted to 4X3 list :
trans = [[row[i] for row in matrix] for i in range(4)]
print(trans)
# Equivalent to the following , But the above method is more concise
transposed = []
for i in range(4):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
Use del Statement can delete an element from a list by index rather than value . This is with the use of pop() Return a value different from . It can be used del Statement to remove a cut from the list , Or empty the entire list ( The method we introduced earlier is to assign an empty list to the cut ). for example :
a = [1, 2, 3, 456, 789, 1234.5]
del a[0] #[2, 3, 456, 789, 1234.5]
del a[2:4] #[2, 3, 1234.5]
del a[:]
It can also be used. del Delete entity variable :
del a
Tuples consist of several comma separated values , for example :
t = 12345, 54321, 'hello!'
t[0] # 12345
t #(12345, 54321, 'hello!')
u = t, (1, 2, 3, 4, 5)
u # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Tuples are always output in parentheses , In order to correctly express the nested structure . There may or may not be parentheses when typing , But brackets are usually necessary ( If the tuple is part of a larger expression ).
A set is a set of unordered non repeating elements . Basic functions include relationship testing and de duplication .
You can use braces ({}) Create set . Be careful : If you want to create an empty collection , You have to use set() instead of {} ; The latter creates an empty dictionary , In the next section, we will introduce this data structure .
Here is a simple code example ( On-line python3 Environmental Science ):
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # Delete duplicate
# result {'orange', 'banana', 'pear', 'apple'}
'orange' in basket # Detection member
# result True
'crabgrass' in basket
# result False
# The following demonstrates the operation of two sets
a = set('abracadabra')
b = set('alacazam')
a # a The only letter in the dictionary
# result {'a', 'r', 'b', 'c', 'd'}
a - b # stay a Letters in , But not here. b in
# result {'r', 'd', 'b'}
a | b # stay a or b Letters in
# result {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b # stay a and b There are letters in all languages
# result {'a', 'c'}
a ^ b # stay a or b Letters in , But not at the same time a and b in
# result {'r', 'd', 'b', 'm', 'z', 'l'}
Another very useful Python The built-in data type is dictionary .
A sequence is indexed by consecutive integers , The difference is , The dictionary is indexed by keywords , Keywords can be any immutable type , It's usually a string or a number .
The best way to understand a dictionary is to think of it as an unordered key => Value to set . In the same dictionary , Keywords must be different from each other .
A pair of braces creates an empty dictionary :{}.
company = {'ShowMeAI': 1234, 'Baidu': 5678}
company['guido'] = 4127
company
# result {'Baidu': 5678, 'guido': 4127, 'ShowMeAI': 1234}
company['ShowMeAI']
# result 1234
del company['Baidu']
company['irv'] = 4127
company
# result {'guido': 4127, 'irv': 4127, 'ShowMeAI': 1234}
list(company.keys())
# result ['irv', 'guido', 'ShowMeAI']
sorted(company.keys())
# result ['guido', 'irv', 'ShowMeAI']
'guido' in company
# result True
'ShowMeAI' not in company
# result False
Constructors dict() Building a dictionary directly from a list of key value pairs tuples . Besides , The dictionary can be used to create a dictionary of arbitrary values and values :
dict([('ShowMeAI', 1234), ('Baidu', 5678)])
# result {'ShowMeAI': 1234, 'Baidu': 5678}
{x: x**2 for x in (2, 4, 6)}
# result {2: 4, 4: 16, 6: 36}
If the keyword is just a simple string , It is sometimes more convenient to specify key value pairs with keyword parameters :
dict(ShowMeAI=1234, Baidu=5678)
# result {'ShowMeAI': 1234, 'Baidu': 5678}
When traversing through the dictionary , Keywords and corresponding values can be used items() Methods read it out at the same time :
knights = {'ShowMeAI': 1234, 'Baidu': 5678}
for k, v in knights.items():
print(k, v)
When traversing through a sequence , Index location and corresponding value can be used enumerate() Function at the same time :
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# 0 tic
# 1 tac
# 2 toe
Traversing two or more sequences at the same time , have access to zip() Combine :
questions = ['name', 'age', 'color']
answers = ['ShowMeAI', '30', 'blue']
for q, a in zip(questions, answers):
print('What is the {0}? It is {1}.'.format(q, a))
# What is the name? It is ShowMeAI.
# What is the quest? It is 30.
# What is the color? It is blue.
To traverse a sequence in reverse , First specify the sequence , And then call reversed() function :
for i in reversed(range(1, 10, 2)):
print(i)
# 9
# 7
# 5
# 3
# 1
To traverse a sequence in order , Use sorted() Function returns a sorted sequence , The original value is not modified :
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
# apple
# banana
# orange
# pear
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :