In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the Python list, dictionaries, tuples and collection instance analysis related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Python list, dictionaries, tuples and collection instance analysis article will have a harvest, let's take a look.
Listing 1. List
What is a list?
Variables can store one element, while lists can store N elements.
Lists are equivalent to arrays in other languages.
The difference is that lists in python can store multiple different types of elements.
The Av10 # variable stores an object's id (that is, address) lst= ['hello','world',98] print (id (lst)) print (type (lst)) print (lst)
Note: the variable stores the id of one element, while the list stores the id of multiple elements, as shown in the figure:
Lst saves the id of the list, and each location of the list stores the id of each element, so we can use the list to store many different kinds of elements.
two。 Creation and deletion of lists
Create:
① [,] uses square brackets, and elements use', 'such as lst1= [' hello','world',11].
② calls built-in functions list () such as lst2=list (['hello','world',11])
Create an empty list
List3= [] or list3=list ()
Features of the list:
The list elements are arranged in order
Index mapping unique element
The positive order of the index is positive, starting from 0, the reverse order is negative, starting from-1
Can store duplicate data
Mixed storage of any data type
Dynamically allocate and reclaim memory as needed.
3. The query operation of the list gets the index of the specified element in the list
Index (element)
If there are multiple identical elements in a neutral list, only the index of the first element in the same element is returned.
If the element of the query is not in the list, an error ValueError will appear
You can look between the specified start and end.
Forward index from 0 to Nmuri 1, such as lst [0]
Reverse index from-N to-1, such as lst [- N]
Specified index does not exist, IndexError appears
Get multiple elements in the list (slices)
Syntax:
List name [start: end: step]
Result of the slice: copy of the original list fragment
Range of slices: [start,end)
Step defaults to 1: abbreviated to [start: end]
Lst=] lst1= LST [2: 6:2] print (lst) print (lst1) print ('original list', id (lst)) print ('slice', id (lst1)) # slice is a new list object
When step is positive, slice back from start.
The first element of the slice defaults to the last element of the list
The last element of the slice defaults to the first element of the list.
Lst=] print (LST [1: 6:2]) # [20,40,60] print (lst [: 6:2]) # [10,30,50] print (LST [1:: 2]) # [20,40,60,80]
When step is negative, slice forward from start
Lst= [lst [:-1]) # [90, 80, 70, 60, 50, 40, 30, 20, 10] print (LST [6::-2]) # [70, 50, 30, 10] print (LST [6: 0 print 2]) # [70, 50, 30] print (lst [: 2rel 2]) # [90, 70, 50] to determine whether the specified element exists in the list
Syntax:
Element in list name
Element not in list name
Traversal of list elements
Syntax:
For iteration variable in list name:
Operation
Print (10 in lst) print (100 not in lst) for item in lst: print (item) 4. Addition, deletion and modification of list elements; addition of list elements; lst= [10 hello','world'; 20; 30; 40; 50; 50; 60; 70; 80; 90] lst1= ['hello','world'] lst2= [' python'] 66 append 88] # four methods # the first method is to add an element lst.append (100) print (lst [9]) lst.append (lst1) # add lst1 as an element at the end of lst print (lst) # the second kind of extend () add at least one element lst.extend (lst1) # add lst1 as two elements at the end of lst print (lst) # third Insert () add an element lst.insert (1) 11) # insert 11print (lst) # the fourth slice adds at least one element LST [1:] = lst2 # anywhere in the list essentially adds a list print (lst) to the cut part
Deletion of list elements lst= [10 remove 20 print (lst) # second pop () Delete the element at a specified index location; delete the last element without specifying an index There is no error in the specified index IndexErrorlst.pop (3) print (lst) # the third slice deletes at least one element at a time, but the slice produces a new list object new_list=lst [1:3] # not if lst [1:3] = [] print (lst) # fourth clear () empty list lst.clear () print (lst) # fifth del delete list del lstprint (lst) # error
Modification of list elements lst= [10, lst 20, 30, 40, 50] print (lst) # the first gives a new value to the element of the specified index lst [1] = 11print (lst) # the second assigns a new value to the specified slice, lst [1:3:] = [666, 777, 888, 999,] print (lst)
5. Sorting of list elements # two sorting methods print ('first method:') lst= [11Magne7, 9999, 86, 59108] print (lst,id (lst)) # the first calls the sort () method, and all elements in the list are sorted from smallest to largest by default. # you can specify reverse=True to sort in descending order lst.sort () # equivalent to lst.sort (reverse=False) print (lst,id (lst)) # sorting in ascending order lst.sort (reverse=True) print (lst) # sorting in descending order print ('second method:') lst= [11 lst= (lst,id (lst) # call the built-in function sorted (), and you can specify the sort in descending order The original list does not change and a new list object new_list=sorted (lst) print (lst,id (lst)) print (new_list,id (new_list)) # ascending sort desc_list=sorted (lst,reverse=True) print (desc_list,id (desc_list)) # descending sort will be generated
6. List generation
That is, the formula for generating the list.
Syntax:
List name = [list element expression for i in range (,)]
Note: expressions generally contain custom variables I
Lst= [iMagi for i in range (1jin10)] print (lst) # output as [1, 4, 9, 16, 25, 36, 49, 64, 81] VII, dictionary 1. What is a dictionary?
Variable sequence: a sequence, such as a list, that makes additions, deletions and modifications.
Immutable sequence: cannot add, delete or modify on the basis of the original, such as string, integer
Dictionary is one of the built-in data structures in python. Like lists, it is a variable sequence.
Store data in the form of key-value pairs, and the dictionary is an unordered sequence; (list single dogs, dictionaries in pairs)
Syntax: for example
Scores= {'Zhang San': 99J'Li Si': 66, 'Wang Wu': 11}
(: before is called a key, and after: is called a value)
Dictionary schematic diagram: (1, 2, 3 represents the order of elements)
Unlike the first position of the first element in the list and the second position of the second element, the location of the elements in the dictionary is independent of the entry order, but the position calculated by the hash function.
two。 The principle of dictionary
The implementation principle of the dictionary is similar to that of us looking up the dictionary in reality. In reality, we first look up the corresponding page number according to the partial radical or pinyin. In Python, we first calculate the key value of the element through the hash function, and then find the value according to the key value.
3. Creation and deletion of dictionaries # two ways to create dictionaries # the first is {} score= {'Zhang San': 11'Li Si': 9999 'Wang Wu': 7} print (score,type (score)) # the second uses the built-in function dict () people=dict (name=' Su Mu', age=20) print (people,type (people)) # empty dictionary a = {} # or a=dict () print (aQuery type (a))
4. The query operation of the dictionary the acquisition of elements in the dictionary score= {'Zhang San': 11pi'Li Si': 99BI 'Wang Wu': 7 'age':20} print (score) # two methods to get the value of the elements in the dictionary according to the key # the first [' key'] print (score ['Zhang San']) print (score ['age']) # the second. Get () method print (score.get (' Zhang San')) # difference between the two methods: # print (score ['Su Mu']) error report: exception: KeyErrorprint (score.get ('Su Mu')) # normal operation The result is the default value of the output setting when the element does not exist in the Noneprint (score.get ('Chufeng', 66)) # dictionary
The difference between the two methods:
[] if the specified key does not exist in the dictionary, an exception will occur
Get () returns None if the specified key does not exist in the dictionary, and you can set the default value by parameter to return if the specified key does not exist
Key's judgment score= {'Zhang San': 11je'Li Si': 99je 'Wang Wu': 7 the key specified by in returns Trueprint ('Zhang San' in score) # not in specified key does not exist in the dictionary return Trueprint ('Zhang San' not in score) 5. Additions, deletions, and deletions of dictionary elements score= {'Zhang San': 11meme'Li Si': 99nd 'Wang Wu': 7 print print (score) # del deletes a key value pair del score ['Zhang San'] print (score) # clear () empties the dictionary element score.clear () print (score)
The addition and modification of dictionary elements score= {'Zhang San': 11je'Li Si': 99je 'Wang Wu': 7 ~ (th) print (score) score ['Su Mu'] = 66 # add print (score) score ['Su Mu'] = 88 # modify print (score)
6. Get dictionary view
There are three ways:
Keys () gets all the key in the dictionary
Values () gets all the value in the dictionary
Items () gets all the key.value key-value pairs in the dictionary
Score= {'Zhang San': 11je'Li Si': 99je 'Wang Wu': 7 keya=score.keys (score) # keys () get all the keya=score.keys () print (a) print (list (a)) in the dictionary # you can use list to convert the view of all key into a list # values () get all the valueb=score.values () print (b) in the dictionary Type (b)) print (list (b)) # items () gets all the key.value keys in the dictionary. The list elements converted by c=score.items () print (c) print (list (c)) # are tuples.
7. Ergodic of dictionary elements score= {'Zhang San': 11 recordings'Li Si': 99je 'Wang Wu': 7 recordings lane 20} for i in score: print (iGraine score [I], score.get (I))
I outputs keys, and the next two outputs values
8. Dictionary generation
That is, the formula for generating a dictionary.
The built-in function zip () takes iterable objects as parameters, packages the corresponding elements in the object into a tuple, and then returns a list of these tuples.
Syntax:
{expression for dictionary key: expression for dictionary value for custom variable for key, custom variable in zip for value (iterable object 1, iterative object 2)}
Lst1= ['Hello','World','Python'] lst2= [10 key:value for key,value in zip (lst1,lst2)} print (a) b = {key.upper (): value for key,value in zip (lst1,lst2)} print (b)
If the number of elements in two iterable objects is not the same, the one with fewer elements shall prevail.
9. Summarize the characteristics of the dictionary
All elements in the dictionary are key-value key-value pairs. Key cannot be repeated, repetition will be overwritten, and value can be repeated.
The elements in the dictionary are unordered
The key in the dictionary must be an immutable object; (the variable sequence cannot calculate the hash)
Dictionaries can also be dynamically scaled as needed.
Dictionaries waste a lot of memory and are data structures that trade space for time.
8. Tuple 1. What is a tuple?
We already know in the dictionary that variable sequences and immutable sequences are repeated below:
Variable sequence: you can add, delete and change the sequence without changing the address of the object. Such as lists, dictionaries
Immutable sequence: no addition and deletion operations, such as strings, tuples.
So tuples are also one of the built-in data structures in Python, and they are immutable sequences.
Note: Xiao Mu thinks that the key to immutability depends on whether the memory address of the element has changed.
two。 How tuples are created
Created in three ways
# there are three ways to create tuples # the first way is to use parentheses () parentheses directly to save a = ('Python','Hello',11) # or a parenthesis Pythonium (a)) # the second is to use the built-in function tuple () b=tuple ((' Python','yyds',666)) print (bforce type (b)) # the third element that contains only one tuple requires commas and parentheses Without comma, the system considers it to be the basic data type int, etc. C = (888,) # parentheses can be saved. Comma cannot omit print (cpentetype (c)) # creation of empty tuples T1 = () t2=tuple ()
3. Traversal of tuples
You can output tuple elements by index, but if you don't know the number of elements, you can use for in
T = (10, [20jue 30], 40jue 50) # first index print (t [0]) # second for infor item int: print (item) 4. Matters needing attention
First of all, why should we design tuples as immutable sequences?
Because of this design, in a multitasking environment, such as multi-person cooperation, there is no problem that the object needs to be locked when one person manipulates the object, because the tuple itself is an immutable sequence and can only be read. We should also try to use immutable sequences in the program.
Note:
What is stored in the tuple is the reference (address) of the object
If the objects in the tuple are themselves immutable, you can no longer reference other objects
If the data in the tuple is a mutable object, the reference to the mutable object is not allowed to change, but the data can be changed.
T = (10, [20jue 30], 40jue 50) # t [1] = 100error t [1] .append (10) print (t) # list is a variable sequence, you can add elements to the list, but the memory address of the list remains the same, set 1. What is a collection?
Collection is one of the built-in data structures provided by Python
Like lists and dictionaries, they all belong to variable type sequences.
Collections are dictionaries that have no value value.
The storage location is also calculated by the hash function.
two。 Creation of a collection
There are two ways:
Note: just as the keys in the dictionary cannot be repeated, so can the elements in the collection.
# two ways # the first is {} S1 = {'hello','world','python',11} print (S1 s2=set (S1)) # the second uses the built-in function set () s2=set (range (6)) print (S2 (S2)) s3=set ([1mlml2) 5pd5]) # converts the elements in the list into a collection At the same time, remove the repeating element print (s3jue type (S3)) s4=set ((2LJ 11) 7J 78J 66)) # convert the tuple into a set print (S4) s5=set ('python') # string into a set print (S5 (S5)) # define an empty set cannot be directly used {} otherwise it is an empty dictionary s6=set () print (S6)
3. Add, delete, modify and check the collection elements to determine whether the collection elements exist or not-- in not ins= {10 ins 20 print 30 50 not ins 99} print (s) print (10 ins) print (100 not ins) two new methods add () update () s = {10 print (s) # the first method calls the add () method, adding one element at a time s.add (100) print (s) # the second method calls update () Add at least one element s.update ({666888999}) # add all elements in the collection print (s) s.update ([6666 8888 s.update]) # add all elements in the list to the collection print (s) s.update ((66686 88888) 99999) # add all elements in the tuple to the collection print (s)
Deletion of set elements # four methods: remove () discard () pop () clear () s = {10 print () 20 print () 40 50 print 99} print (s) # the first remove method deletes one specified element at a time, if the specified element does not have an error KeyErrors.remove (99) print (s) # the second discard () method deletes one specified element at a time, if there is no exception in the specified element, there is no exception s.discard (100) print (s) # third pop () method Delete only one element at a time s.pop () # cannot specify the parameter print (s) # the fourth clear () method clears the collection s.clear () print (s)
4. The relationship between sets
The main relationships between the two sets are equality, subset, superset, and intersection. Let's use the code to see how to judge:
S1 = {10 print (s2.issubset (S1)) # can be used to judge whether S2 is a subset of S1. Issubset () method print (s2.issubset (S1)) # can be used to determine whether S1 is a superset of S2. Issuperset (s1.issuperset (S2)) # can be used to judge that there is no intersection between the two sets. The method isdisjoint can be used to judge whether S2 is a subset of S1. The mathematical operation of the set S1 = {10men20, 30, 40, 50, 99, S2 = {10, 10, 20, 30, 80, 80, 1. Find the intersection print (s1.intersection (S2)) print (S1 & S2) # 2. The union set print (s1.union (S2)) print (S1 | S2) # 3. Find the difference set print (s1.difference (S2)) print (s1-s2) # 4. Find the symmetric difference print (s1.symmetric_difference (S2)) print (S1 ^ S2)
Note: the original set is unchanged after the mathematical operation.
6. Set generation
A set generator is a formula used to generate a set.
S = {iTun2 for i in range (5)} print (s)
Note: sets, dictionaries and lists all have generators, but tuples do not have generators because they are immutable sequences.
This is the end of the article on "Python lists, dictionaries, tuples, and collection instance analysis". Thank you for reading! I believe you all have a certain understanding of "Python lists, dictionaries, tuples and set case analysis". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.