python data structure

python data structure

List

Lists in Python are variable. This is the most important feature that distinguishes them from strings and tuples. In one sentence, lists can be modified, but strings and tuples cannot.
The following is a list in Python

>>> a =[66.25,333,333,1,1234.5]>>>print(a.count(333), a.count(66.25), a.count('x'))210>>> a.insert(2,-1)>>> a.append(333)>>> a
[66.25,333,- 1,333,1,1234.5,333]>>> a.index(333)1>>> a.remove(333)>>> a
[66.25,- 1,333,1,1234.5,333]>>> a.reverse()>>> a
[333,1234.5,1,333,- 1,66.25]>>> a.sort()>>> a
[-1,1,66.25,333,333,1234.5]

Note: Methods like insert, remove or sort to modify the list have no return value.

Use the list as a stack

The list method makes the list easy to use as a stack. The stack is used as a specific data structure. The element that enters first is released last (last in, first out). Use the append() method to add an element to the top of the stack. You can release an element from the top of the stack by using the pop() method without specifying an index. E.g:

>>> stack =[3,4,5]>>> stack.append(6)>>> stack.append(7)>>> stack
[3,4,5,6,7]>>> stack.pop()7>>> stack
[3,4,5,6]>>> stack.pop()6>>> stack.pop()5>>> stack
[3,4]

Use the list as a queue

You can also use the list as a queue, but the first element added in the queue is taken out first (first in, first out); you need to use the deque module to convert the list into a queue, and use the popleft function to release the elements, but take the list It is not efficient for such purposes. Adding or popping elements at the end of the list is fast, but inserting or popping 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(["Eric","John","Michael"])  #Convert the list to queue mode
>>> queue.append("Terry")           #Add elements to the end of the list
>>> queue.append("Graham")>>> queue.popleft()                 #Release element
' Eric'>>> queue.popleft()'John'>>> queue                           
deque(['Michael','Terry','Graham'])

List comprehension

List comprehensions provide an easy way to create lists from sequences. Usually the application program applies some operations to each element of a certain sequence, and uses the result obtained as the element to generate a new list, or creates a sub-sequence according to certain judgment conditions.
Each list comprehension is followed by an expression for for, and then there are zero or more for or if clauses. The return result is a list generated from the subsequent for and if contexts based on the expression. If you want the expression to deduce a tuple, you must use parentheses.
Here we multiply each value in the list by three to obtain a new list:

vec=[1,2,3]
list1=[x*3for x in vec]  #List comprehension

print(list1)

operation result:

[3, 6, 9]

From the above example, we can see that the so-called deduction is a mixed expression written in square brackets, which will return a new list object (if square brackets are used)

You can also generate a two-dimensional list:

vec=[1,2,3]
list1=[[x,x**3]for x in vec] #Adding a square bracket to the list comprehension will generate a two-dimensional list

print(list1)

operation result:

[[1, 1], [2, 8], [3, 27]]

You can also call a method one by one for each element in the sequence:

>>> freshfruit =['  banana','  loganberry ','passion fruit  ']>>>[weapon.strip()for weapon in freshfruit]  #Call a method one by one
[' banana','loganberry','passion fruit']

Some elements can be filtered using if statements:

>>>[3* x for x in vec if x >3]  #Only generate elements greater than three
[12,18]>>>[3* x for x in vec if x <2]  #Only generate elements less than two
[]

Here are some demonstrations of loops and other techniques:

>>> vec1 =[2,4,6]>>> vec2 =[4,3,-9]>>>[x*y for x in vec1 for y in vec2]   #This is a double loop, the y loop is nested in the x loop
[8,6,- 18,16,12,- 36,24,18,- 54] # This is also a double loop. The difference from the above one is that this one uses the addition operator
>>>[ x+y for x in vec1 for y in vec2][6,5,-7,8,7,-5,10,9,-3]>>>[vec1[i]*vec2[i]for i inrange(len(vec1))] #Use the length of vec1 as the number of cycles to multiply the elements in the same subscript of the two lists
[8,12,-54]

List comprehensions can use complex expressions or nested functions:

# Here the range of round defines how many decimal places are retained after the decimal point
>>>[ str(round(355/113, i))for i inrange(1,6)]  #Convert the floating-point number generated by the round function to a string type through the str function
['3.1','3.14','3.142','3.1416','3.14159']

Nested list comprehension

Python lists can also be nested, which is a two-dimensional list.
The following example shows a 3X4 matrix list:

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

The following example converts a 3X4 matrix list into a 4X3 list:

print([[row[i]for row in matrix]for i inrange(4)])

operation result:

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

The above conversion is a new list generated by list comprehension, in addition to this, it can also be implemented with a loop:

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

j=1for i inrange(4):for row in matrix:print("[",row[i],"]",end=" ")if j%3==0:print()
  j +=1

operation result:

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

The following examples can also be implemented:

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

transposed =[]for i inrange(4):
 transposed.append([row[i]for row in matrix]) #This is to add new elements to an empty list after a list comprehension is generated

print(transposed)

operation result:

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

There is another way to achieve this, which is more cumbersome:

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

transposed =[]for i inrange(4):

 transposed_row =[]for row in matrix:
  transposed_row.append(row[i]) #Add the traversed elements to an empty list
 transposed.append(transposed_row) #Then add this list object

print(transposed)

operation result:

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

del statement

Use the del statement to delete an element from a list by index rather than value. This is different from using pop() to return a value. You can use the del statement to delete a cut from the list, or empty the entire list (the method we introduced before is to assign an empty list to the cut). E.g:

>>> a =[-1,1,66.25,333,333,1234.5]>>> del a[0]>>> a
[1,66.25,333,333,1234.5]>>> del a[2:4]>>> a
[1,66.25,1234.5]>>> del a[:]>>> a
[]

Tuples and sequences

Tuples can consist of several comma-separated values, for example:

>>> t =12345,54321,'hello!'>>> t[0]12345>>>t(12345,54321,'hello!')>>> # Tuples may be nested:... u = t,(1,2,3,4,5)>>>u((12345,54321,'hello!'),(1,2,3,4,5))

As you can see, tuples always have parentheses in the output to facilitate the correct expression of nested structures. The input may or may not have parentheses, but parentheses are usually required (if the tuple is part of a larger expression).

We all know that the value in a tuple is immutable, but if the value in the tuple is a mutable object, modifying the value of the mutable object will cause the value of the tuple to also change:

a =[1,2,3,4]
b =[5,6,7,8]
c =[9,10,11,12]
tuple1 = a, b, c  #Lists combined together will become tuple types

print(tuple1)
del b[1:4]  #What changed here is the value of the b list
print(tuple1)

operation result:

([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])  
([1, 2, 3, 4], [5], [9, 10, 11, 12])

Collection

A set is a set that is unordered and does not repeat elements. Basic functions include relationship testing and elimination of duplicate elements.
You need to use curly braces {} to create a collection. Note: If you want to create an empty set, you must use set() instead of {}; the latter creates an empty dictionary.
The following is a simple demonstration:

>>> basket ={'apple','orange','apple','pear','orange','banana'}>>>print(basket)                      #Duplicates will be deleted automatically, and the order may be different each time you print, because the collection is out of order
{' orange','banana','pear','apple'}>>>'orange'in basket                 #Check members
True
>>>' crabgrass'in basket
False

>>> # The following demonstrates the operation of two sets
...>>> a =set('abracadabra')>>> b =set('alacazam')>>> a                                  #the only letter in a
{' a','r','b','c','d'}>>> a - b                              #Letters in a but not in b
{' r','d','b'}>>> a | b                              #The letter in a or b
{' a','c','r','d','b','m','z','l'}>>> a & b                              #Letters in both a and b
{' a','c'}>>> a ^ b                              #Letters in a or b, but not in a and b at the same time

Sets also support comprehensions:

>>> a ={x for x in'abracadabra'if x not in'abc'}>>> a
{' r','d'}

Dictionary

Another very useful Python built-in data type is the dictionary.
Sequences are indexed by consecutive integers. The difference is that a dictionary is indexed by keywords. The keywords can be of any immutable type, usually strings or numbers.
The best way to understand a dictionary is to think of it as an unordered collection of key/value pairs. Within the same dictionary, the key must be unique.
Use a pair of braces to create an empty dictionary: {}
This is a simple example of dictionary usage:

>>> tel ={'jack':4098,'sape':4139} #Create a dictionary
>>> tel['guido']=4127  #Add a pair of keys to the dictionary
>>> tel
{' sape':4139,'guido':4127,'jack':4098}>>> tel['jack']  #Get the value of the key
4098>>> del tel['sape']  #Delete a key-value pair
>>> tel['irv']=4127  #Add a pair of key values to the dictionary, the values can be repeated
>>> tel
{' guido':4127,'irv':4127,'jack':4098}>>>list(tel.keys())  #Get all the keys in the dictionary and convert them to a list
[' irv','guido','jack']>>>sorted(tel.keys())  #Get all the keys in the dictionary, convert them to a list and then sort them
[' guido','irv','jack']>>>'guido'in tel  #Check members
True
>>>' jack' not in tel
False

The constructor dict() can directly construct a dictionary from a list of key-value pairs. If there is a fixed pattern, the list comprehension specifies specific key-value pairs:

>>> dict([('sape',4139),('guido',4127),('jack',4098)]) #The list is a tuple of key-value pairs, constructed into a dictionary type through dict
{' sape':4139,'jack':4098,'guido':4127}

If the keyword is just a simple string, it is sometimes more convenient to specify key-value pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098){'sape':4139,'jack':4098,'guido':4127}

In addition, dictionary derivation can be used to create expression dictionaries of arbitrary keys and values:

>>>{ x: x**2for x in(2,4,6)}  #x is the key, and the second power of x is the value
{2:4,4:16,6:36}

Traversal skills

When traversing in the dictionary, the keywords and corresponding values can be read at the same time using the items() method:

>>> knights ={'gallahad':'the pure','robin':'the brave'}>>>for k, v in knights.items():  #Each cycle can read a pair of key values
... print(k, v)...
gallahad the pure
robin the brave

When traversing in the sequence, the subscript position and corresponding value can be obtained at the same time using the enumerate() function:

>>> for i, v inenumerate(['tic','tac','toe']): #Enumerate can get the subscript and the corresponding value at the same time
... print(i, v)...0 tic
1 tac
2 toe

To traverse two or more sequences at the same time, they can be combined using the zip() function:

>>> questions =['name','quest','favorite color']>>> answers =['lancelot','the holy grail','blue']>>>for q, a inzip(questions, answers):...print('What is your {0}?  It is {1}.'.format(q, a))...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To traverse a sequence in reverse, first specify the sequence, and then call the reversed() function. reversed is used to reverse the sequence:

>>> for i inreversed(range(1,10,2)):...print(i)...97531
list1 =[1,2,3,4,5,6]for i inreversed(list1):print(i, end=" ")

operation result:

6 5 4 3 2 1

To traverse a sequence in order, use the sorted() function to return a sorted sequence without modifying the original value. sorted is used for sorting. The difference with the sort function is that sorted will generate a new list:

>>> basket =['apple','orange','apple','pear','orange','banana']>>>for f insorted(set(basket)):...print(f)...
apple
banana
orange
pear

The sort function only sorts the original list, and does not generate a new list object:

list2 =[84,56,12,65,2,4,85,123]
list.sort(list2)for x in list2:print(x, end=" ")

operation result:

2 4 12 56 65 84 85 123

Recommended Posts

python data structure
Python common data structure collation
Python data structure and algorithm
02. Python data types
Python data model
Python data format-CSV
Python data analysis-data update
Python data analysis-apply function
Python data analysis-data selection
Python data analysis-data establishment
Python Data Science: Neural Networks
Python parsing variable length structure
Python3 crawler data cleaning analysis
Python parses simple XML data
Python Data Science: Logistic Regression
Python Data Science: Regularization Methods
Python Data Science: Linear Regression
Python Faker data forgery module
Python Data Science: Chi-Square Test
Python Data Science: Linear Regression Diagnosis
Python realizes online microblog data visualization
Is python suitable for data mining
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Automatically generate data analysis report with Python
Python string
Python access to npy format data examples
Python descriptor
Python basics 2
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Java or Python for big data analysis
Python multitasking-threads
Python uses pandas to process Excel data
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5