Four basic data structures built into Python

This article is used to learn the four basic data structures built into Python! ! !

import numpy as np
'''Lists of Python3 data structures can be modified, while strings and tuples cannot'''

# Represents a list, the list elements are strings, numbers, lists
ls = ['name','age',1,['python','c++']]

#get the number of list elements
print (len (ls))

#Get the element of the specified index in the list, use the minus sign to extract the elements from the back to the front and so on
print (ls [0: 3])
print (ls [-3: -1])

#Get the index of the specified element and use an element as the entry parameter of the method
print( ls.index('name') )

#Get the number of times the child element or substring appears in the list or string, the second and third entry parameters are the search range
print( ls.count('name') )

#Add a list to the end of this list
ls = [1,2,3]
ls.append([1,2,3])#append method changes the ls structure
print (ls)

# Extend the elements of a list to this list
ls.extend([1,2,3])
print (ls)

#Insert an element or list at the specified index
ls.insert(1, 'hobby')
print (ls)

#reversely sort the elements in the list
ls.reverse()
print (ls)

#copy list
ls2 = ls.copy()
print( ls2 )
ls2 = ls [:]
print( ls2 )

#Remove the specified element directly
ls.remove('hobby')
print (ls)

#delete the element corresponding to the list index
ls.pop(1)
print (ls)

#delete all elements in the list
ls.clear()
print (ls)

#List is a mutable object that can operate on internal content changes and sort digital elements
ls = [3,2,1]
ls.sort ()
print (ls)

#Extract list elements, slice operation
print (ls [: 3])
print (ls [1: 3])
print (ls [-2: -1])

#Expand the multidimensional list elements into a one-dimensional list
ls=[[1,2],["yu","yu"]]
ls = [j for i in ls for j in i]
print (ls)

#First array the list structure, then expand the data into an array
ls = [[1,2], [3,4]]
arr = np.array(ls)
arr.flatten()
print( arr )

#First matrix the list structure
Mat = np.mat (ls)
# Expand this matrix and convert it to an array
print( Mat.flatten().A )
print(np.shape(Mat.flatten().A))
#Get the first-dimensional array after expansion of this matrix
print( Mat.flatten().A[0] )

'''Use the list as a stack, last in first out, use the append() method to add elements to the top of the stack,
Use the pop() method without specifying an index to release the element from the top of the stack'''
stack = [1,2,3]
stack.pop()
print( stack )

'''Use the list as a queue, first in first out'''
from collections import deque
queue = deque(['name','age'])
queue.append('weight')
queue.popleft()
print( queue )

'''List comprehension, write expressions in lists, from the most basic methods to one line of code
range(1,11,2) left closed and right open, the third element is the interval size of the slice operation, python2 uses xrange()'''
print( list(range(1,11,2)) )

ls = []
for i in range(1,11,2):
    ls.append(i*i)
print (ls)

ls = [i*i for i in list(range(1,11))]
print (ls)

# use if as filter
print( [i*i for i in range(1,11) if i%2==0] )

print( [m+n for m in "ABC" for n in 'XYZ'] )
print( [i+j for i,j in zip("ABC","XYZ")] )

#Use complex expressions or nested functions, i is the number of digits after the decimal point round() to obtain the quotient of the specified number of decimal points
print( round(355/133,3) )
ls = [str(round(355/113,i)) for i in range(1,6)]
print (ls)

#Convert a 3*2 matrix list to a 2*3 list
ls = [[1,2], [3,4], [5,6]]
print( [[row[i] for row in ls] for i in range(len(ls[0]))] )

ls2=[]
for i in range(2):
    ls2.append([row[i] for row in ls])
print( ls2 )

#Convert list element data type
ls = ['1', '2', '3']
print( [int(i) for i in ls] )
print( [float(i) for i in ls] )
ls = [1,2,3]
print( [str(i) for i in ls] )

#Operation of elements of two lists
print( [i*0.2+j*0.8 for i,j in zip( [1,2,3],[4,5,6] )] )

'''Use the del statement to delete an element from a list by index instead of value, and to delete a cut'''
#delete the element with index 0
of ls [0]
#delete elements with index 2-3
of the ls [0: 2]
#delete all elements
of them[:]
print (ls)

#delete entity variable
of them
#print (ls)

# Strings are immutable objects, you can only use the replace method
Str = 'yuyu'
print( Str.replace('l','L') )


'''
A tuple consists of comma-separated values
'''
tp = tuple('name')
tp = ('name','age',('weight'))
for t in tp:
   print(t)
#Convert tuple to list
print( list(tp) )


'''
Sequences are indexed by consecutive integers, but dictionaries are indexed by keys, which are any immutable type, usually strings or numbers.
Within the same dictionary, the keywords must be different from each other
'''
dic={'name':'liyu','age':23}
print( dict(name='liyu',age=23) )
The #dict() method builds a dictionary from a list of tuples
print( dict([('name','liyu'),('age',23)]) )
#Create a dictionary using comprehension
print( {key:key**2 for key in (1,2)} )

#Get the value corresponding to the key
print( dic.get('name') )
print( dic['name'] )

#judgment key
if 'name' in dic:
    print( dic['name'] )
else:
    print( 'not found' )

#Insert new key-value pair
dic['weight']=68

#delete key value
dic.pop('weight')
#del dic['weight']

#Get the key\value in the form of a list
print( list(dic.keys()) )
print( list(dic.values()) )

#Iterative output keyIterative output valueIterative output key and value
for key in dic.keys():
    print(key)
for value in dic.values():
    print(value)
for k,v in dic.items():
    print (k, v)


'''
A set is an unordered and non-repeating set of elements. The basic function is to eliminate duplicate elements or test the relationship between sets.
'''
se = {'li','yu','li'}
print (se)

se2 = set('liyuLiYu')
se3 = set('liyuName')
print(se2)
print(se3)

Letters in #2, but not in 3
print( se2-se3 )
# letter in 2 or 3
print( se2|se3 )
# letters in 2 and 3
print( se2&se3 )
# letters in 2 or 3, but not XOR in both 2 and 3
print( se2^se3 )

#Set comprehension
print( {x for x in 'liyuname' if x not in 'ly'} )

#Convert other data structures, such as lists into sets
se = set ([1,1,2,3])
se.add(4)
se.remove(4)
print (se)

References:

1. Liao Xuefeng "Python2.7 Tutorial"


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325861276&siteId=291194637