5.1 understanding combined data types
-
The common sequence types in Python are string, list and tuple.
-
Sequences in Python support two-way indexes: forward increasing index and reverse decreasing index. The forward increasing index increases from left to right. The index of the first element is 0, the index of the second element is 1, and so on; Reverse decrement index decrements from right to left. The index of the first element is - 1, the index of the second element is - 2, and so on.
-
Python collections have three characteristics: certainty, heterogeneity and disorder. Python requires that the elements put into the set must be of immutable type. Integer, floating point, string type and tuple in Python belong to immutable type, and list, dictionary and set themselves belong to variable data type.
Certainty: given a set, whether any element is in the set is determined.
Dissimilarity: the elements in the collection are different from each other.
Disorder: there is no order for the elements in the set. Sets with different orders but the same elements can be regarded as the same set.
-
The mapping type stores elements in the form of key value pairs, and there is a mapping relationship between keys and values in key value pairs. Dictionary (dict) is the only built-in mapping type in Python. The keys of the dictionary must comply with the following two principles:
- Each key can only correspond to one value. The same key is not allowed to appear repeatedly in the dictionary.
- Keys in the dictionary are immutable types.
5.2 list
Store multiple values, and the values can be accessed according to the index.
Separate multiple values of any type with commas in [].
5.2. 1 create list
You can either use the bracket "[]" directly or use the built-in list() function to create it quickly.
Format:
list_one = [] # use [] to create an empty list
li_two = list() # use list() to create an empty list
iteration
Iteration is a repeated process, constantly taking the output of the previous time as the input or initial value of the next time.
'''iteration''' '''Traversing subscript list Two uses of''' #The first method L=['steven','kate','jack'] for i in range(len(L)): #Ergodic subscript print('Hello',L[i]) #Print the list value corresponding to the subscript #The second method L=['steven','kate','jack'] for i in L: #Traversal element print('Hello',i) #Print element '''Traversal subscript free dict''' #By default, the key of dict iteration is d={'a':1,'b':2,'c':3} for key in d: #Subscripts are not required print(key) #If you want to iterate over value, you can use for value in d.values() d={'a':1,'b':2,'c':3} for value in d.values(): #value of iterative dict print(value) #If you want to iterate over key and value at the same time, you can use for key,value in d.items() d={'a':1,'b':2,'c':3} for key,value in d.items(): print(key,value)
Iteratable object
in Python, the object that supports iterating to obtain data through the for... in... Statement is an iterative object.
Iteratable types include string, list, set, dictionary and file.
Use the isinstance() function to determine whether the target is an iteratable object, and return True to indicate that it is an iteratable object.
'''Iteratable object''' #Example 1 from collections.abc import Iterable #Iterable object of collections module print(isinstance('abcde', Iterable)) #Judge whether the character production can be iterated #Example 2 from collections.abc import Iterable #Iterable object of collections module ls = [3,4,5] print(isinstance(ls, Iterable)) #Determine whether the list can be iterated
5.2. 2 access list elements
The elements in the list can be accessed by index or slice, or in turn in a loop.
#Example L=['python',1,1.2,[5,'High number']]
1. Value by index
print(L) print(L[0]) print(L[-1]) #Reverse value print(L[3]) #Positive value
2. Value by slice
print(L[0:3]) print(L[0:3:1]) print(L[0:3:2]) print(L[0:3:3])
3. Value by cycle
for i in L: print(i)
5.2. 3 add list elements
Adding elements to a list is a very common list operation. Python provides methods such as append(), extend(), and insert().
#Example L=['python',1,1.2,[5,'High number']]
1. append() adds an element to the end of the list
L.append('English') print(L)
2. extend() adds all the elements of another sequence to the end of the list
The list [] in parentheses is also appended at the end
L.extend(['Physics','Chemistry']) print(L)
3. insert() inserts an element before the specified index position
L.insert(0,'application') print(L)
5.2. 4 element sorting
The sorting of the list is to arrange the elements according to certain regulations. The common sorting methods in the list are sort(), reverse(), and sorted().
#Example list=[8,5,3,7,2]
1. sort() ordered elements will overwrite the original list elements without generating a new list
list.sort() print(list)
2. reverse() reverses the list, that is, the elements in the original list are arranged and stored from right to left
list.reverse() print(list)
3. sorted() generates a new sorted list, and the sorting operation will not affect the original list
list_new=sorted(list) print(list_new) print(list)
5.2. 5 delete list
The common ways to delete list elements are del statement, remove() method, pop() method and clear() method.
#Example R=[6,'Mao gai',[9,'Ideological and political'],'shell']
1. del statement to delete the element at the specified position in the list
del R[0] print(R)
2. remove() method to remove the first matching element in the list
R.remove(6) R.remove('shell') print(R)
3. pop() method to remove an element from the list. If no specific element is specified, it will be removed
The last element in the list
R.pop(2) print(R)
4. clear() method, clear the list
R.clear() print(R)
5.2. 6 list derivation
List derivation is a compound expression that conforms to Python syntax rules. It is used to build a list that meets specific needs according to the existing list in a concise way.
The basic format of list derivation is as follows:
[exp for x in list]
#The operation is preceded by an iteration
#Example 1 list1=[ x * x for x in range(1,10)] print(list1) #Example 2 list2=[x for x in range(100)] print(list2) #Example 3 list3=[m+n for m in 'ABC' for n in 'XYZ'] print(list3)
5.3 tuple
Record multiple values. When multiple values do not need to be changed, tuples are more appropriate.
Separate multiple values of any type with commas within ().
5.3. 1 create tuple
In addition to using () to build tuples, you can also use the built-in function tuple() to build tuples.
Format:
t1 = () # use () to build tuples
t2 = tuple() # use tuple to build tuples
5.3. 2 access tuple element
1. Value by index
2. Value by slice
3. Traversal tuple
'''Example''' T= ('p','y','t', 'h', 'o','n') #Value by index print(T) print(T[0]) print(T[1]) print(T[-1]) #Reverse value print(T[3]) #Positive value #Slice value print(T[0:4]) print(T[0:4:1]) print(T[0:4:2]) print(T[0:3:3]) #Traversal tuple for i in T: print(i)
When creating a tuple with parentheses "()", if the tuple contains only one element, you need to add a comma after the element to ensure that the Python interpreter can recognize it as a tuple type.
t1 = ('python') t2 = ('python',) print(type(t1)) print(type(t2))
5.4 assembly
Multiple values separated by commas in {}.
Element cannot be repeated.
The elements in the collection are unordered.
5.4. 1 create a collection
Python's collection (set) itself is a mutable type, but Python requires that the elements placed in the collection must be of an immutable type. The brace "{}" or the built-in function set() can build a collection.
Format:
s1 = {1} # build collection with {}
s2 = set([1,2]) # use set to build tuples
Note: an empty set cannot be created with {} (a dictionary variable is created with {} without elements), and an empty set can only be created with the set() function.
set_demo1 = {} set_demo2 = set() print(type(set_demo1)) print(type(set_demo2))
Collections are mutable, and elements in collections can be dynamically added or deleted. Python provides some built-in methods to operate collections. The common built-in methods are as follows:
The set can also be created by derivation. The format of the set derivation is similar to that of the list derivation, except that the set derivation is surrounded by braces "{}", as follows:
{exp for x in set if cond}
5.5 dictionary
Separate multiple key:value elements with commas in {}, where value can be any data type, and key should usually be of string type.
5.5. 1 create dictionary
In addition to using "{}" to create a dictionary, you can also use the built-in function dict to create a dictionary.
Format:
d1 = {'A': 123, 12: 'python'} # use {} to build a collection
D2 = dict ({'a':'123 ',' B ':'135'}) # use dict to build tuples
Note: dictionary elements are out of order, and key values must be unique
5.5. 2 access to dictionaries
#Example info = {'name': 'Jack','age':23,'height':185}
5.5. 3 addition and modification of elements
Element addition
Dictionary addition without re assignment
List additions and modifications must be indexes where the operation exists
info['addr']='Changsha' print(info)
or
info.update(sco=98) print(info)
Modification of element
info['name']='Mary' print(info)
or
info.update({'name':'Mary'}) print(info)
5.5. 4 deletion of dictionary elements
Python supports deleting elements from dictionaries through pop(), popitem(), and clear() methods.
1. pop(): deletes the specified element in the dictionary according to the specified key value
2. popitem(): randomly delete elements from the dictionary
3. clear(): clear the elements in the dictionary
'''Dictionary deletion''' info = {'name': 'Jack','age':23,'height':185,'addr':'Changsha'} print(info) #pop() info.pop('addr') print(info) #popitem() info.popitem() print(info) #clear() info.clear() print(info)
5.5. 5 dictionary derivation
The dictionary derivation is surrounded by braces "{}" on the outside and contains keys and values inside. The specific format is as follows:
{new_key:new_value for key,value in dict.items()}
- The dictionary derivation can be used to quickly exchange keys and values in the dictionary. Examples are as follows:
'''Dictionary derivation''' old_dict = {'name': 'Jack','age':23,'height':185} new_dict = {value:key for key,value in old_dict.items()} print(new_dict)