This paper summarizes the common Python data structure, and with an example to illustrate, I believe that the reader has a certain reference value.
Generally , the data structures commonly found in Python can be collectively referred to as Containers (container). sequences (such as lists and tuples), mappings (such as dictionaries) , and collections (sets) are three main types of containers.
First, sequence (list, tuple, and string)
Each element in the sequence has its own number. There are 6 types of built-in sequences in Python. where lists and tuples are the most common types. Other include strings, Unicode strings, buffer objects, and Xrange objects. The following tables, tuples, and strings are highlighted below.
1, List
The list is variable, which is the most important feature that distinguishes it from strings and tuples: The list can be modified and the strings and tuples cannot.
(1), create
You can create a list in the following ways:
list1=[' Hello ', ' world ']
print list1
list2=[1,2,3]
print List2
Output:
[' Hello ', ' world ']
[1, 2, 3]
As you can see, this is created in a way that is very similar to an array in JavaScript.
(2), List function
The list function (in fact the list is a type rather than a function) is useful for creating lists of strings:
List3=list ("Hello")
print List3
Output:
[' H ', ' e ', ' l ', ' l ', ' O ']
2. META Group
Tuples, like lists, are also a sequence, and the only difference is that tuples cannot be modified (strings actually have this feature).
(1), create
t1=1,2,3
t2= "Jeffreyzhao", "Cnblogs"
t3= (1,2,3,4) t4= () t5= (
1,)
print T1,t2,t3,t4,t5
Output:
(1, 2, 3) (' Jeffreyzhao ', ' cnblogs ') (1, 2, 3, 4) () (1,)
From the above we can analyze the following:
A, comma separated some values, the tuple is automatically created to complete;
B, the tuple most of the time is enclosed by parentheses;
C, empty tuples can be represented by parentheses that do not contain content;
D, a tuple containing only one value, you must add a comma (,);
(2), tuple function
The tuple function is almost the same as the list function of a sequence: take a sequence (note is a sequence) as an argument and convert it to a tuple. If the argument is a tuple, the argument is returned as is:
T1=tuple ([1,2,3])
t2=tuple ("Jeff")
T3=tuple ((1,2,3))
print T1
print t2
print T3
t4=tuple ( 123)
Print T45
Output:
(1, 2, 3)
(' J ', ' e ', ' f ', ' F ')
(1, 2, 3)
Traceback (most recent call last):
File "F:\Python\test.py", line 7, in <module>
T4=tuple (123)
TypeError: ' int ' object is not iterable
3, String
(1) Create
str1= ' Hello world '
print str1
print str1[0 to
C in str1:
print C
Output:
Hello World
h e l l o
w
o
r
L
D
(2) formatting
String formatting is implemented using the string format operator, which is the percent sign.
str1= ' hello,%s '% ' world. '
Print str1
The right-hand operand of the format operator can be anything, and if it is a tuple or a mapping type (such as a dictionary), the string formatting will be different.
strs= (' Hello ', ' world ') #元组
str1= '%s,%s '% strs
print str1
d={' h ': ' Hello ', ' W ': ' World '} #字典
str1= '% (h ) s,% (w) s '% d
print str1
Output:
Note: If you need a converted tuple to exist as part of a transformation expression, you must enclose it in parentheses :
str1= '%s,%s '% ' Hello ', ' World '
print str1
Output:
Traceback (most recent):
File "F:\Python\test.py", line 2, in <module> str1= '
%s,%s '% ' Hello ', ' World '
typeerror:not enough arguments for format string
If you need to output% of this special character, there is no doubt that we would think of escaping, but the correct way to handle Python is as follows:
str1= '%s%% '%
print str1
Output:
to format numbers, you typically need to control the width and precision of the output :
From Math import pi
str1= '%.2f '% pi #精度2
print str1
str1= '%10f '% pi #字段宽10
print str1
str1= '%10.2 F '% pi #字段宽10, precision 2
print str1
Output:
String formatting also contains a number of other rich conversion types that can be referenced in the official documentation.
Python also provides another way to format values in the string module: the template string. It works like a variable substitution in many Unix shells, as follows:
From string import Template
str1=template (' $x, $y! ')
Str1=str1.substitute (x= ' Hello ', y= ' world ')
print str1
Output:
If the replacement field is part of a word, then the parameter name must be enclosed in parentheses to accurately indicate the end:
From string import Template
str1=template (' hello,w${x}d! ')
Str1=str1.substitute (x= ' orl ')
print str1
Output:
To output the $ character, you can use the $$ output:
From string import Template
str1=template (' $x $$ ')
str1=str1.substitute (x= ')
print str1
Output:
In addition to keyword parameters, template strings can be formatted using dictionary variables to provide key-value pairs:
From string import Template
d={' h ': ' Hello ', ' W ': ' World '}
str1=template (' $h, $w! ')
Str1=str1.substitute (d)
print str1
Output:
In addition to formatting, Python strings have a number of practical methods in place, which can be referenced in the official documentation, not listed here.
4. General sequence operation (method)
From lists, tuples, and strings, you can "abstract" some of the public common methods of a sequence (not what you would think of as crud), including indexing (indexing), fragmentation (sliceing), plus (adding), Multiply (multiplying) and check whether an element belongs to a member of a sequence. In addition, there are built-in functions such as calculating the sequence length, the maximum minimum element, and so on.
(1) Index
str1= ' Hello '
nums=[1,2,3,4]
t1= (123,234,345)
print str1[0]
print nums[1]
print t1[2]
Output
The index starts at 0 (left-to-right), and all sequences can be indexed in this way. Amazingly, the index can start from the last position (right to left), and the number is-1:
str1= ' Hello '
nums=[1,2,3,4]
t1= (123,234,345)
print str1[-1]
print nums[-2]
print t1[-3]
Output:
(2) Fragment
A fragment operation is used to access elements within a certain range. The fragment is implemented by two indexes separated by a colon:
Nums=range ()
print nums
print Nums[1:5] Print
nums[6:10]
print nums[1:]
print nums[-3:-1]
print nums[-3:] #包括序列结尾的元素, empty the last index
print nums[:] #复制整个序列
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4]
[6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[7, 8]
[7, 8, 9]
Different step lengths, with different outputs:
Nums=range (a)
print nums
print nums[0:10] #默认步长为1 equivalent to nums[1:5:1]
print nums[0:10:2] #步长为2
Print Nums[0:10:3] #步长为3
# #print nums[0:10:0] #步长为0
print nums[0:10:-2] #步长为-2
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 3, 6, 9]
[]
(3) Sequence addition
str1= ' Hello '
str2= ' world '
print str1+str2
num1=[1,2,3]
num2=[2,3,4]
print num1+num2
Print Str1+num1
Output:
Hello World
[1, 2, 3, 2, 3, 4]
Traceback (most recent call last):
File "F:\Python\test.py", line 7, in <module>
Print Str1+num1
Typeerror:cannot concatenate ' str ' and ' list ' objects
(4) multiplication
Print [none]*10
str1= ' Hello '
print str1*2
num1=[1,2]
print num1*2
print str1*num1
Output:
[None, None, none, none, none, none, none, none, none, none]
Hellohello
[1, 2, 1, 2]
Traceback (most recent call last):
File "F:\Python\test.py", line 5, in <module>
Print Str1*num1
Typeerror:can ' t multiply sequence by non-int of type ' list '
(5) Membership
The in operator is used to check whether an object is a member of a sequence (or other type) (that is, an element):
str1= ' Hello '
print ' h ' in str1
print ' h ' into str1
num1=[1,2]
print 1 in NUM1
Output:
(6) Length, maximum minimum value
The built-in functions Len, Max, and Min can return the number, maximum, and minimum elements of the contained elements in the sequence.
str1= ' Hello '
print len (str1) print
max (str1)
print min (str1)
num1=[1,2,1,4,123]
print len (NUM1)
Print Max (NUM1)
print min (NUM1)
Output:
Ii. Mapping (dictionary)
Each element in the map has a name, as you know, the name of the professional name called the key. A dictionary (also called a hash table) is the only built-in mapping type in Python.
1. Key type
The keys of a dictionary can be numbers, strings, or tuples, and the keys must be unique. In Python, numbers, strings, and tuples are all designed to be immutable types, and common lists and sets are mutable, so lists and collections cannot be keys to dictionaries. The key can be any immutable type, which is the most powerful of the dictionaries in Python.
list1=["Hello,world"]
set1=set ([123])
d={}
d[1]=1
print d
d[list1]= "Hello World."
d[set1]=123
Print D
Output:
Traceback (most recent call last):
File "F:\Python\test.py", line 6, in <module>
D[list1]= "Hello world."
Typeerror:unhashable type: ' List '
2, automatically add
Even if the key does not exist in the dictionary, you can assign it a value so that the dictionary creates a new item.
3. Membership
The expression item in D (D is a dictionary) looks for the key (ContainsKey) instead of the value (Containsvalue).
The strength of the Python dictionary also includes a number of commonly used operations that can be referenced in the official documentation, not listed here.
Thinking: Based on our experience with strongly typed languages, such as C # and Java, are we sure that the dictionaries in Python are thread safe?
Third, the collection
Collection (set) is introduced in Python 2.3, which is typically created directly using a newer version of Python, as follows:
Strs=set ([' Jeff ', ' Wong ', ' cnblogs '])
Nums=set (range (10))
It seems that a collection is constructed from sequences (or other objects that can be iterated). Several important features and methods of the set are as follows:
1, the copy is ignored
The collection is primarily used to check membership, so the replica is ignored, as shown in the following example, the output is the same as the collection content.
Set1=set ([0,1,2,3,0,1,2,3,4,5])
print Set1
set2=set ([0,1,2,3,4,5])
print Set2
The output is as follows:
Set ([0, 1, 2, 3, 4, 5])
set ([0, 1, 2, 3, 4, 5])
2, the order of the elements of the collection is arbitrary
This is very much like a dictionary, and it can be easily understood that a dictionary with no value is set.
Strs=set ([' Jeff ', ' Wong ', ' cnblogs '])
print STRs
The output is as follows:
Set ([' Wong ', ' cnblogs ', ' Jeff '])
3. Common methods of collection
A, intersection union
Set1=set ([1,2,3])
set2=set ([2,3,4])
set3=set1.union (set2)
print set1
print Set2
print Set3
Output:
Set ([1, 2, 3]) set ([
2, 3, 4]) set
([1, 2, 3, 4])
The Union operation returns the set of two sets and does not change the original collection. Using the bitwise AND (OR) operator "|" Can get the same result:
Set1=set ([1,2,3])
set2=set ([2,3,4])
set3=set1|set2
print set1
print Set2
print Set3
Output is the same result as the union above.
Other common operations include & (intersection), <=,>=,-, copy (), and so on, not listed here.
Set1=set ([1,2,3])
set2=set ([2,3,4])
set3=set1&set2
print set1
print set2
print Set3
Print Set3.issubset (Set1)
set4=set1.copy ()
print set4
print Set4 is Set1
The output is as follows:
Set ([1, 2, 3]) set ([
2, 3, 4]) set ([2, 3])
True Set ([1,
2, 3])
False
b, add and remove
The method for adding and removing sequences is very similar to the official documentation:
Set1=set ([1])
print Set1
set1.add (2)
print Set1
set1.remove (2)
print Set1
print Set1
print in Set1
set1.remove (#移除不存在的项)
Output:
Set ([1]) Set ([
1, 2]) set ([
1]) set ([
1])
False
Traceback (most recent call last):
File "F:\Python\test.py", line 9, in <module>
Set1.remove (#移除不存在的项)
Keyerror:29
4, Frozenset
The collection is mutable, so it cannot be used as a key to the dictionary. The collection itself can contain only immutable values, so it cannot contain other collections:
Set1=set ([1])
set2=set ([2])
Set1.add (Set2)
The output is as follows:
Traceback (most recent call last):
File "F:\Python\test.py", line 3, in <module>
Set1.add (Set2)
Typeerror:unhashable type: ' Set '
You can use the Frozenset type to represent a set of immutable (hash) columns:
Set1=set ([1])
set2=set ([2])
Set1.add (Frozenset (Set2))
print Set1
Output:
Set ([1, Frozenset ([2])])