Graphical python | data structure

Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/83
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source

Python 3 data structure

There are a large number of data structures and containers in Python for programming. In this section, we summarize the previous knowledge points and expand some new knowledge to introduce Python data structures.

1.Python list

In Python, lists are variable, which is the most important feature that distinguishes them from strings and tuples. In a word, lists can be modified, while strings and tuples cannot.

For details of Python list, please refer to the preface Python list and Application

Here are the methods of listing in Python:

methoddescribe
list.append(x)Adding an element to the end of the list is equivalent to a[len(a):] = [x].
list.extend(L)Expand the list by adding all elements of the specified list, which is equivalent 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 before it. For example, a.insert(0, x) will be inserted before the whole list, and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x)Delete the first element with a value of x in the list. If there is no such element, an error will be returned.
list.pop([i])Removes an element from the specified location in the list and returns it. If no index is specified, a.pop() returns the last element. The element is removed from the list. (the square brackets around i in the method indicate that this parameter is optional, rather than requiring you to enter a square bracket. You will often encounter such a mark in the Python library reference manual.)
list.clear()Remove all items from the list, equal to del a [:].
list.index(x)Returns the index of the first element in the list whose value is x. If there is no matching element, an error will be returned.
list.count(x)Returns the number of times x appears in the list.
list.sort()Sort the elements in the list.
list.reverse()Invert the elements in the list.
list.copy()Returns a shallow copy of the list, equal to a [:].

The following example demonstrates most of the methods of listing( Online Python 3 environment):

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

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

Note: methods such as insert, remove or sort that modify the list do not return a value.

2. Use the list as a stack

The list method makes it easy to use the list as a stack. As a specific data structure, the first entry element is released last (LIFO). You can add an element to the top of the stack with the append() method. A pop() method that does not specify an index can release an element from the top of the stack.

Refer to the following code( Online Python 3 environment):

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 take out the first element added in the queue; However, it is not efficient to use lists for such purposes. Adding or popping elements at the end of the list is fast, but inserting or popping elements from the head of the list is not fast (because all 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 an easy way to create a list from a sequence. Usually, the application program applies some operations to each element of a sequence, uses the results obtained as the elements to generate a new list, or creates a subsequence according to the determined judgment conditions.

Each list derivation is followed by an expression after for, followed by zero to more for or if clauses. The return result is a list generated from the subsequent for and if context according to the expression. If you want the expression to derive a tuple, you must use parentheses.

vec = [1, 2, 3]
# Multiply each value in the list by three to 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 value before forming a new list:
cmp_x_square = [[x, x**2] for x in vec]
print(cmp_x_square)

Operation results

[3, 6, 9]
[[1, 1], [2, 4], [3, 9]]

The 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', 'apply']

In the list derivation, you can use the if clause to build a filter to filter the generated results:

[3*x for x in vec if x > 2]
# Results [9]
[3*x for x in vec if x < 3]
# Results [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
# Results [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
# Results [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
# Results [4, 10, 18]

5. Nested list parsing

Python lists can also be nested.

The following code shows the matrix list of 3X4( Online Python 3 environment):

matrix = [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9, 10, 11, 12],
       ]

# Convert 3X4 matrix list 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 statement

Using the Del statement, you can delete an element from a list by index rather than by value. This is different from using pop() to return a value. You can delete a cut from the list with del statement or empty the whole 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[:]

You can also delete entity variables with del:

del a

7. Tuple

Tuples consist of several comma separated values, such as:

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 with parentheses to facilitate the correct expression of nested structures. There may or may not be parentheses when entering, but parentheses are usually required (if the tuple is part of a larger expression).

8. Assemble

A collection is an unordered set of non repeating elements. Basic functions include relationship testing and de duplication.

You can create a collection with braces ({}). Note: if you want to create an empty set, you must use set() instead of {}; The latter creates an empty dictionary. We will introduce this data structure in the next section.

The following is a simple code example( Online Python 3 environment):

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # Delete duplicate
# Results {'orange', 'banana', 'pear', 'apple'}

'orange' in basket                 # Test member
# Result True

'crabgrass' in basket
# Result False

# The following demonstrates the operation of the two sets
a = set('abracadabra')
b = set('alacazam')

a                                  # The only letter in a
# Results {'a', 'R', 'B', 'C','d '}

a - b                              # The letter in a, but not in b
# Result {'R','d ',' B '}

a | b                              # Letters in a or b
# Results {'a', 'C', 'R','d ',' B ','m', 'Z', 'l'}

a & b                              # Letters in both a and b
# Result {'a', 'c'}

a ^ b                              # A letter in a or b, but not in both a and b
# Results {'R','d ',' B ','m', 'Z', 'l'}

9. Dictionary

Another very useful Python built-in data type is a dictionary.

Sequences are indexed by continuous integers. Unlike this, dictionaries are indexed by keywords, which can be of any immutable type, usually string or numeric value.

The best way to understand a dictionary is to think of it as an unordered set of key = > value pairs. Keywords must be different from each other within the same dictionary.

A pair of braces creates an empty dictionary: {}.

company = {'ShowMeAI': 1234, 'Baidu': 5678}
company['guido'] = 4127

company
# Results {Baidu ': 5678,' Guido ': 4127,' showmeai ': 1234}

company['ShowMeAI']
# Result 1234

del company['Baidu']
company['irv'] = 4127
company
# Results {'guido': 4127, 'irv': 4127, 'ShowMeAI': 1234}

list(company.keys())
# Results ['irv ',' Guido ',' showmeai ']

sorted(company.keys())
# Results ['guido', 'irv', 'ShowMeAI']

'guido' in company
# Result True

'ShowMeAI' not in company
# Result False

The constructor dict() builds a dictionary directly from the list of key value pair tuples. In addition, the key and the value of the dictionary can be used to create any dictionary:

dict([('ShowMeAI', 1234), ('Baidu', 5678)])
# Results {'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)
# Results {'ShowMeAI': 1234, 'Baidu': 5678}

10. Traversal skills

When traversing the dictionary, the keyword and the corresponding value can be interpreted simultaneously using the items() method:

knights = {'ShowMeAI': 1234, 'Baidu': 5678}
for k, v in knights.items():
   print(k, v)

When traversing the sequence, the index position and corresponding value can be obtained simultaneously by using the enumerate() function:

for i, v in enumerate(['tic', 'tac', 'toe']):
   print(i, v)
# 0 tic
# 1 tac
# 2 toe

To traverse two or more sequences at the same time, you can use zip() to 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 backwards, first specify the sequence and then call the reversed() function:

for i in reversed(range(1, 10, 2)):
   print(i)

# 9
# 7
# 5
# 3
# 1

To traverse a sequence in order, use the sorted() function to return a sorted sequence without modifying the original value:

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 github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!

The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:

Extended references

ShowMeAI related articles recommended

ShowMeAI series tutorial recommendations

Keywords: Python Programming data structure AI Data Mining

Added by sakaveli on Wed, 23 Feb 2022 09:24:37 +0200