Python language is simple and clear, and the same function can be achieved with less code. Among them, four data types built into Python are indispensable, namely list, tuple, dict and set. The following is a brief summary of them.
catalogue
Literally means a set. In Python, the elements in the list are indicated by square brackets [], and the list can be defined as follows:
L = [12,' China', 19.998]
As you can see, the types of elements do not need to be the same. Of course, you can also define an empty list:
L = []
The list in Python is ordered, so if you want to access the list, you should obviously access it by serial number, just like the subscript of the array, starting from 0:
& gt& gt& gt print L[0]
12
Never cross the line, or you will report an error.
& gt& gt& gt print L[3]
Backtracking (last call):
File "< standard input >, line 1, in< module & gt
Index error: List index is out of range.
The list can also be accessed in reverse order, and the serial number is represented by a subscript, such as "x from the bottom". For example, the subscript-1 indicates the last element:
& gt& gt& gtL = [12,' China', 19.998]
& gt& gt& gt print L[- 1]
19.998
-4 is obviously out of line.
& gt& gt& gt print L[-4]
Backtracking (last call):
File "& ltpyshell#2 >, line 1, in< module & gt
Print L[-4]
Index error: List index is out of range.
& gt& gt& gt
The List is added to the tail by the built-in append () method, and to the specified position by the insert () method (subscript starts from 0):
& gt& gt& gtL = [12,' China', 19.998]
& gt& gt& gtL.append ('Jack')
& gt& gt& gt print l
[12,' China', 19.998,' Jack']
& gt& gt& gtl. Insert (1, 3. 14)
& gt& gt& gt print l
[12,3.14,' China', 19.998,' Jack']
& gt& gt& gt
Delete the last tail element through pop (), or you can specify a parameter to delete the specified location:
& gt& gt& gt Pop Music ()
Jack
& gt& gt& gt print l
[12,3.14,' China', 19.998]
& gt& gt& gt Pop Music (0)
12
& gt& gt& gt print l
[3. 14,' China', 19.998]
You can also copy and replace with subscripts.
& gt& gt& gtL[ 1] =' USA'
& gt& gt& gt print l
[3. 14,' USA', 19.998]
tuple
A tuple can be regarded as an "immutable" list, and access is also indicated by subscripts and brackets ():
& gt& gt& gtt = (3. 14,' China',' Jason')
& gt& gt& gt print t
(3. 14, "China", "Jason")
However, you cannot reassign a replacement:
& gt& gt& gtt[ 1] =' USA'
Backtracking (last call):
File "& ltpyshell#2 1 >, line 1, in< module & gt
T[ 1] =' USA'
Typeerror:' tuple' object does not support item allocation.
There are also no pop, insert and append methods.
You can create an empty element tuple:
t =()
Or a single-element tuple (such as adding a comma to prevent and declare a plastic ambiguity):
t = (3. 14,)
So what's the use of this type of tuple? You know, if you want a function to return multiple return values, you just need to return a tuple, because a tuple contains multiple values and is immutable (just like final in java). Of course, tuples are also variable, such as:
& gt& gt& gtt = (3. 14,' China',' Jason', ['A',' B'])
& gt& gt& gt print t
(3. 14,' China',' Jason', ['A',' B'])
& gt& gt& gtL = t[3]
& gt& gt& gtL[0] = 122
& gt& gt& gtL[ 1] = 233
& gt& gt& gt print t
(3. 14,' China',' Jason', [122,233])
This is because Tuple's so-called invariance means that the pointing position is immutable, because the fourth element in this example is not the basic type, but the list type, so the position of the list pointed by T is unchanged, but the content of the list itself can be changed, because the allocation of the list itself in memory is discontinuous.
dictionary
Dict is a very important data type in Python. Just like its literal meaning, it is a walking dictionary, but it is actually a key-value key-value pair. Similar to HashMap, you can use curly braces to define a structure similar to that of C language:
& gt& gt& gtd = {
Adam: In' 95,
Lisa: 85 years old,
Bart: 59 years old,
Paul: 75
}
& gt& gt& gt print d
{'Lisa': 85,' Paul': 75,' Adam': 95,' Bart': 59}
You can see that the printed results are all in the format of Key:Value, and its length can be calculated by len function (List, tuple can also be used):
& gt& gt& gt lens (d)
four
You can add elements directly in dict through key-value pairs:
& gt& gt& gt print d
{'Lisa': 85,' Paul': 75,' Adam': 95,' Bart': 59}
& gt& gt& gtd[' Jones'] = 99
& gt& gt& gt print d
{'Lisa': 85,' Paul': 75,' Adam': 95,' Jones': 99,' Bart': 59}
List and Tuple use subscripts to access content, while Dict uses keys: (String, integer, floating-point and tuple can all be used as dict keys).
& gt& gt& gt print d['Adam']
95
If the item does not exist, an error will be reported:
& gt& gt& gt print d['Jack']
Backtracking (last call):
File "& ltpyshell#40 >, line 1, in< module & gt
Print d['Jack']
Critical error: "Jack"
So it's best to check whether the key exists before visiting:
& gt& gt& gt If "Adam" in D: print "exist key".
Existing key
Or directly use the insurance acquisition method:
& gt& gt& gt print d.get('Adam')
95
& gt& gt& gt print d.get ('Jason')
nobody
As for traversing a dict, it is actually traversing the set of all its keys, and then using this key to obtain the corresponding value:
& gt& gt& gt for key:print key,':', d.get(key) in D.
Lisa: 85 years old.
Paul: 75
Adam: 95
Bart: 59
Dict has some characteristics:
Search speed is fast. Whether it is 10 or 65438+ 100000, the speed is the same, but it takes up a lot of memory. List takes up less memory, but the search speed is slow. It's like the difference between an array and a linked list. Arrays don't know how much space to open up, so they often open up a lot of space at the beginning, but it is very fast to search directly through subscripts. The linked list takes up a small space, but it must be traversed in order when searching, which leads to a slow speed.
There is no order. Dict is unordered, and List is an ordered set, so you can't use Dict to store ordered sets.
Keys are immutable and values are changeable. Once a key-value pair is added to dict, its corresponding key cannot be changed, but the value can be changed. So List can't be used as the key of Dict, but it can be used as the value:
& gt& gt& gt print d
{'Lisa': 85,' Paul': 75,' Adam': 95,' Jones': 99,' Bart': 59}
& gt& gt& gtd['NewList'] = [ 12,23,' Jack']
& gt& gt& gt print d
{'Bart': 59,' NewList': [ 12,23,' Jack'],' Adam': 95,' Jone': 99,' Lisa': 85,' Paul': 75}
Keys cannot be duplicated. (In the following example, a' Jone' is added: 0, but actually the key' jone' already exists, so only the original value is changed. )
& gt& gt& gt print d
{'Bart': 59,' NewList': [ 12,23,' Jack'],' Adam': 95,' Jone': 99,' Lisa': 85,' Paul': 75}
& gt& gt& gtd[' Jones'] = 0
& gt& gt& gt print d
{'Bart': 59,' NewList': [ 12,23,' Jack'],' Adam': 95,' Jone': 0,' Lisa': 85,' Paul': 75}
Dict merge, how to merge two Dicts into one, you can use the dict function:
& gt& gt& gtd 1 = {'Mike': 12,' Jack': 19}
& gt& gt& gtd2 = {'jone':22,' ivy': 17}
& gt& gt& gtd merge = dict(d 1 . items()+D2 . items())
& gt& gt& gt print data merge
{'Mike': 12,' Jack': 19,' Jones': 22,' Ivy': 17}
or
& gt& gt& gtdMerge2 = dict(d 1,**d2)
& gt& gt& gt Print data merge 2
{'Mike': 12,' Jack': 19,' Jones': 22,' Ivy': 17}
Method 2 is much faster than method 1, and method 2 is equivalent to:
& gt& gt& gtdMerge3 = dict(d 1)
& gt& gt& gtdMerge3.update(d2)
& gt& gt& gt print data merge
{'Mike': 12,' Jack': 19,' Jones': 22,' Ivy': 17}
set up
Set is like pulling a key in Dict, similar to a list, but the content cannot be repeated. It is created by calling the set () method:
& gt& gt& gts = set (['A',' b',' C'])
Just as dict is unordered, set is unordered and cannot contain repeated elements.
The significance of accessing a collection is only to see whether an element is in the collection:
& gt& gt& gt Print "A" in S.
real
& gt& gt& gt Print "D" in S.
wrong
Case is very sensitive.
It is also traversed for:
S = set([ ('Adam', 95), ('Lisa', 85), ('Bart', 59)])
# tuple
For x in s:
Print x[0],':', x[ 1]
& gt& gt& gt
Lisa: 85 years old.
Adam: 95
Bart: 59
Add and delete elements (no duplicates). When adding elements, use the add () method of set:
& gt& gt& gts = set ([1, 2,3])
& gt& gt& gts.add(4)
& gt& gt& gt print s
set([ 1,2,3,4])
If the added element already exists in the collection, add () will not give an error, but it will not be added:
& gt& gt& gts = set ([1, 2,3])
& gt& gt& gts.add(3)
& gt& gt& gt print s
Set ([1, 2,3])
When deleting elements in the collection, use the remove () method of the collection:
& gt& gt& gts = set ([1, 2,3,4])
& gt& gt& gts.remove(4)
& gt& gt& gt print s
Set ([1, 2,3])
If the deleted element does not exist in the collection, remove () will report an error:
& gt& gt& gts = set ([1, 2,3])
& gt& gt& gts.remove(4)
Backtracking (last call):
File "< standard input >, line 1, in< module & gt
Critical error: 4
So if you want to judge whether an element meets some different conditions, set is the best choice. The following example:
Month = set (['January',' February',' March',' April',' May',' June',' July',' August',' September',' October',' November',])
x 1 = 'Feb '
X2 =' Sun'
If x 1 month:
Print "x 1: normal"
Otherwise:
Print "x 1: Error"
If x2 is in months:
Print "x2: Normal"
Otherwise:
Print "x2: Error"
& gt& gt& gt
X 1: ok.
X2: Error