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

Graphical Python | data structure

編輯:Python

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


Python3 data structure

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 .

1.Python list

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 :

Method describe list.append(x) Add an element to the end of the list , amount to a[len(a):] = [x].list.extend(L) Expand the list by adding all the elements of the specified list , amount to a[len(a):] = L.list.insert(i, x) Inserts an element at the specified location . The first parameter is the index of the element to be inserted in front of it , for example a.insert(0, x) Will be inserted before the entire list , and a.insert(len(a), x) amount to a.append(x) .list.remove(x) Delete the value in the list as x The first element of . If there is no such element , It will return an error .list.pop([i]) Remove the element from the specified position in the list , And return it . If no index is specified ,a.pop() Return to the last element . The element is then removed from the list .( In the method i Square brackets on both sides indicate that this parameter is optional , Instead of asking you to enter a square bracket , You will often be in Python This tag is encountered in the library reference manual .)list.clear() Remove all items from the list , be equal to del a[:].list.index(x) The first value in the return list is x The index of the element . If there is no matching element, an error is returned .list.count(x) return x The number of times in the list .list.sort() Sort the elements in the list .list.reverse() The elements in the inverted list .list.copy() Returns a shallow copy of the list , be equal to a[:].

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 .

2. Use the list as a stack

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'] 

3. Use the list as a queue

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'>

4. List derivation

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]

5. Nested list parsing

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)

6.del sentence

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

7. Tuples

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 ).

8. aggregate

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'}

9. Dictionaries

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}

10. Ergodic technique

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

Data and code download

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 :

  • Python Quick reference table

Expand references

  • Python course —Python3 file
  • Python course - Liao Xuefeng's official website

ShowMeAI Recommended articles

  • python Introduce
  • python Installation and environment configuration
  • python Basic grammar
  • python Basic data type
  • python Operator
  • python Condition control and if sentence
  • python Loop statement
  • python while loop
  • python for loop
  • python break sentence
  • python continue sentence
  • python pass sentence
  • python String and operation
  • python list
  • python Tuples
  • python Dictionaries
  • python aggregate
  • python function
  • python Iterators and generators
  • python data structure
  • python modular
  • python File read and write
  • python File and directory operations
  • python Error and exception handling
  • python object-oriented programming
  • python Namespace and scope
  • python Time and date

ShowMeAI A series of tutorials are recommended

  • The illustration Python Programming : From introduction to mastery
  • Graphical data analysis : From introduction to mastery
  • The illustration AI Mathematical basis : From introduction to mastery
  • Illustrate big data technology : From introduction to mastery


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