Sort out common Python Data Structures

Source: Internet
Author: User

Common Data Structures in python can be collectively referred to as containers ). Sequences (such as lists and meta-groups), ing (such as dictionaries), and set are three main containers.

I. Sequence (list, tuples, and strings)

Each element in the sequence has its own number. Python has six built-in sequences. Lists and metadata are the most common types. Others include strings, Unicode strings, buffer objects, and xrange objects. The following describes the list, tuples, and strings.

1. List

The list is variable, which is the most important feature that distinguishes it from strings and metadata. In a word, the list can be modified, but the string and metadata cannot.

(1) Create

You can create a list using the following method:

 
List1 = ['hello', 'World'] print list1list2 = [1, 2, 3] print list2

Output:
['Hello', 'World']
[1, 2, 3]

As you can see, the creation method is very similar to the array in JavaScript.

 

(2) List Functions

The list function (in fact, list is a type rather than a function) is very effective for creating a list of strings:

List3 = List ("hello") print list3

Output:

['H', 'E', 'l', 'l', 'O']

 

2. tuples

Like lists, tuples are also a sequence. The only difference is that tuples cannot be modified (strings also have this feature ).

(1) Create
 
T1 = 1, 2, 3t2 = "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 analysis, we can conclude that:

A. Values are separated by commas (,). The tuples are automatically created;

B. Most of the tuples are enclosed in parentheses;

C. Empty tuples can be represented by parentheses without content;

D. Single-value tuples must contain commas (,);

 

(2) tuple Function

The tuple function is almost the same as the list function of the sequence:Sequence(Note that it is a sequence) as a parameter and converts it to a tuples. If the parameter is a tuple, the parameter is returned as is:

 
T1 = tuple ([123, 3]) T2 = tuple ("Jeff") T3 = tuple (, 3) print t1print t2print t3t4 = tuple () 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 str1print str1 [0] for C in str1: Print C

Output:
Hello World
H
H
E
L
L
O
 
W
O
R
L
D

 

(2) Format

String formatting is implemented using the string formatting operator % Percent.

 
Str1 = 'hello, % s' % 'World. 'print str1

The right operand of the formatting operator can be anything. If it is a tuples or ing type (such as a dictionary), the string formatting will be different.

STRs = ('hello', 'World') # tuples str1 = '% s, % s' % strsprint str1d = {'H': 'hello', 'w ': 'World'} # dictionary str1 = '% (h) s, % (w) s' % dprint str1

Output:

Hello, world
Hello, world

Note: If the tuples to be converted exist as part of the conversion expression, they must be enclosed in parentheses:

 
Str1 = '% s, % s' % 'hello', 'World' print str1

Output:

Traceback (most recent call last ):
File "F: \ Python \ test. py", line 2, in <module>
Str1 = '% s, % s' % 'hello', 'World'
Typeerror: not enough arguments for Format String

If the special character % needs to be output, we will undoubtedly think of escaping, but the correct processing method in python is as follows:

 
Str1 = '% S %' % 100 print str1

Output: 100%

To Format a number, you usually need to control the width and accuracy of the output:

 
From math import pistr1 = '%. 2f '% PI # precision 2 print str1str1 =' % 10f' % PI # field width 10 print str1str1 = '% 10.2f' % PI # field width 10, precision 2 print str1

Output:

3.14
3.141593
3.14

String formatting also contains many other conversion types. For details, refer to the official documentation.

In python, the string module also provides another method for formatting values: Template string. It works like replacing variables in many UNIX shells, as shown below:

 
From string import templatestr1 = template ('$ X, $ y! ') Str1 = str1.substitute (x = 'hello', y = 'World') print str1

Output:

Hello, world!

If the field to be replaced is a part of a word, the parameter name must be enclosed in parentheses to accurately indicate the end:

From string import templatestr1 = template ('hello, W $ {x} D! ') Str1 = str1.substitute (x = 'orl') print str1

Output:

Hello, world!

To output the $ operator, you can use the $ output:

 
From string import templatestr1 = template ('$ x $') str1 = str1.substitute (x = '000000') print str1

Output:100 $

In addition to keyword parameters, the template string can also be formatted using dictionary variables to provide key-value pairs:

From string import templated = {'H': 'hello', 'w': 'World'} str1 = template ('$ H, $ W! ') Str1 = str1.substitute (d) print str1

Output:

Hello, world!

In addition to formatting, Python strings also have many built-in practical methods. For more information, see the official documentation.

 

4. General sequence operations (methods)

Some common methods (not crud) of sequences can be abstracted from lists, tuples, and strings. These operations include: Index and sliceing), add, multiply, and check whether an element belongs to a Sequence member. In addition, there are also built-in functions such as the length of the computing sequence and the maximum and minimum elements.

(1) Index
Str1 = 'hello' Nums = [123,234,345,] T1 = () print str1 [0] print Nums [1] print T1 [2]

Output

H
2
345

The index starts from 0 (left to right). All sequences can be indexed in this way. What's amazing is that the index can start from the last position (from right to left) and the number is-1:

 
Str1 = 'hello' Nums = [123,234,345,] T1 = () print str1 [-1] print Nums [-2] print T1 [-3]

Output:

O
3
123

(2) fragment

The partition operation is used to access elements within a certain range. Sharding is implemented using two indexes separated by colons:

Nums = range (10) print numsprint Nums [] print Nums [] print Nums [1:] print Nums [-3:-1] print Nums [-3:] # contains the elements at the end of the sequence. Leave the last index blank. Print Nums [:] # copy the entire sequence.

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 sizes have different outputs:

 
Nums = range (10) print numsprint Nums [] # The default step size is 1, which is equivalent to Nums [] print Nums [] # The step size is 2 print Nums [] # The step size is 3 ## numprint s [am] # The step size is 0 print Nums [0: 10:-2] # The step size is-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 + str2num1 = [1, 2, 3] num2 = [2, 3, 4] print num1 + num2print 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] * 10str1 = 'hello' print str1 * 2num1 = [1, 2] print num1 * 2 print str1 * num1

Output:

[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 checks whether an object is a member (that is, an element) of a sequence (or another type ):

Str1 = 'hello' print 'H' in str1 print 'H' in str1num1 = [1, 2] print 1 in num1

Output:

False
True
True

(6) length, maximum and minimum

The built-in functions Len, Max, and min are used to return the number, maximum, and minimum of elements contained in the sequence.

 
Str1 = 'hello' print Len (str1) print max (str1) print min (str1) num1 = [123,] print Len (num1) print max (num1) print min (num1)

Output:

5
O
H
5
123
1

 

Ii. ing (dictionary)

Each element in the ing has a name. As you know, this name is a professional name called a key. A dictionary (also called a hash) is the only built-in ing type in Python.

1. Key type

Dictionary keys can be numbers, strings, or tuples. Keys must be unique. In python, numbers, strings, and metadata are designed to be immutable types, while common lists and sets are variable. Therefore, lists and sets cannot be used as Dictionary keys. Keys can be any unchangeable type, which is the most powerful dictionary in Python.

 
List1 = ["Hello, world"] set1 = set ([123]) d = {} d [1] = 1 print dd [list1] = "Hello world. "d [set1] = 123 print d

Output:

{1: 1}

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 a value to it so that the dictionary creates a new item.

 

3. Membership

The expression item in D (D is a dictionary) looks for the containskey instead of the value (containsvalue ).

 

The Python dictionary has many built-in common operation methods. For more information, see the official documentation.

Thinking: based on our experience in using strong-type languages, such as C # and Java, we will certainly ask if the dictionary in python is thread-safe?

 

Iii. Set

Set is introduced in Python 2.3 and can be directly created using a newer version of Python, as shown below:

 
STRs = set (['jeff ', 'wong', 'cnblogs']) Nums = set (range (10 ))

It seems that a set is constructed by sequences (or other iteratable objects. Several important features and methods of the set are as follows:

1. The copy is ignored.

The set is mainly used to check the membership, so the copy is ignored. As shown in the following example, the output set contains the same content.

Set1 = set ([,]) print set1set2 = set ([,]) 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 Set elements is random.

This is very similar to the dictionary. You can simply understand a set as a dictionary without value.

 
STRs = set (['jeff ', 'wong', 'cnblogs']) print STRs

The output is as follows:

Set (['wong ', 'cnblogs', 'jeff'])

 

3. Set common methods

A. Intersection Union

 
Set1 = set ([1, 2, 3]) set2 = set ([2, 3, 4]) set3 = set1.union (set2) print set1print set2print set3

Output:

Set ([1, 2, 3])
Set ([2, 3, 4])
Set ([1, 2, 3, 4])

The union operation returns the union of two sets without changing the original set. Use the bitwise and (or) operator "|" to get the same result:

 
Set1 = set ([1, 2, 3]) set2 = set ([2, 3]) set3 = set1 | set2print set1print set2print set3

Output the same result as the preceding union operation.

Other common operations include & (intersection), <=, >=,-, copy (), and so on.

Set1 = set ([1, 2, 3]) set2 = set ([2, 3]) set3 = set1 & set2print set1print set2print set3print set3.issubset (set1) set4 = set1.copy () print set4print 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. For details, refer to the official documentation:

 
Set1 = set ([1]) print set1set1. Add (2) print set1set1. Remove (2) print set1print set1print 29 in set1set1. Remove (29) # Remove a nonexistent item

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 (29) # Remove a nonexistent item
Keyerror: 29

 

4. frozenset

The set is variable, so it cannot be used as a dictionary key. The set itself can only contain unchangeable values, so it cannot contain other sets:

 
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'

The frozenset type can be used to represent an unchangeable (hashed) set:

 
Set1 = set ([1]) set2 = set ([2]) set1.add (frozenset (set2) print set1

Output:

Set ([1, frozenset ([2])

 

Refer:

Http://www.python.org/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.