Home > Backend Development > Python Tutorial > Detailed explanation of Python's built-in data structures

Detailed explanation of Python's built-in data structures

不言
Release: 2018-04-27 15:36:53
Original
2138 people have browsed it

This article summarizes and introduces 5 built-in data structures in Python and operation examples. It is very detailed. Friends who need it can refer to it.

1. List

list is a data structure in which a series of items can be stored. The items of the list need to be separated by commas and enclosed in a pair of square brackets to indicate that this is a list. The following example is used to show some basic operations of list:

# 定义一个 list 对象 class_list:
class_list = ['Michael', 'Bob', 'Tracy']
# 获得一个 class_list 的长度
print 'class have', len(class_list), 'students'
# 访问class_list中的对象
print 'The 3rd student in class is', class_list[2]
# 往 class_list 中插入对象
class_list.append('Paul')
# 从 class_list 中删除一个项目
del class_list[0]
# 对 class_list 进行排序
class_list.sort()
# 遍历整个class_list中的项目
print 'These students are :',
for student in class_list:
  print student,
Copy after login

The output result is:

class has 3 students
The 3rd student in class is Tracy
These students are: Bob Paul Tracy

There are a few things to note about the above code:

You can add any type of object to the class_list, that is to say, it is not required to be in a list Items are of the same type. You can even insert a list into class_list.
The sorting function acts on itself rather than returning a copy, which is different from the string type because strings cannot be modified.
The end keyword parameter of the print function is used to specify the output after the input is completed. The default is a newline character. The above code uses a space character to replace the newline character.

2. Tuple

tuple is not much different from list in usage and concept. Tuple can be regarded as a Read-only version of the list. This means that once a tuple is defined, it cannot be modified - objects cannot be added or deleted, nor can objects in the tuple be modified.

The items in the tuple should also be separated by commas, and the items should be enclosed in parentheses to indicate that they are a tuple. This parentheses are optional, which means that a tuple can be defined in the following two ways:

t = 'Adam', 'Lisa', 'Bart'
t = ('Adam', 'Lisa', 'Bart')
But omitting the pair of parentheses is not necessarily a good habit. In addition, when the tuple has only one item, there must be a comma after the first item. In this case, t = ('Adam',) should be defined like this. This may seem like an odd constraint, but without the comma, the tuple defined without parentheses becomes t = 'Adam', which is obviously ambiguous.

3. Dictionary

A dictionary can be viewed as a collection of key-value pairs. Keys must be unique, and each key is associated with a value. The key must be an immutable object (such as tuple, numeric type, string). Also note that the key-value pairs in the dictionary are not ordered in any way.

The definition of a dictionary should be in the format d={key1 : value1, key2 : value2, key3 : value3}. Keys and values ​​are separated by colons, key-value pairs are separated by commas, and all key-value pairs are enclosed in braces. Some basic operations are as follows:

# 字典的定义
d = {
  'Adam': 95,
  'Lisa': 85,
  'Bart': 59
}
# 通过键来获取值
print "Adam's score is", d['Adam']
# 删除一个键值对
del d['Bart']
# 遍历字典
for name, score in d.items():
  print '{0} is {1}'.format(name, score)
# 往字典中增加一个键值对
d['Paul'] = 72
# 判断字典中是否存在某键,也可以用 if ab.has_key('Lisa')
if 'Lisa' in d:
  print "Lisa's address is", d['Lisa']
Copy after login

The output result is:

Adam's score is 95
Lisa is 85
Adam is 95
Lisa's address is 85
Copy after login

4. Sequences

The three types introduced above The built-in data structures are all sequences, and the index operation is a basic operation of the sequence. The objects in the sequence can be accessed directly through the subscript operation. Although the subscripting operation has been demonstrated above - queues and tuples are subscripted with numbers, and dictionaries are subscripted with keywords.

The subscript of the sequence starts from 0. In the above example, only the subscript is a positive number. In fact, the subscript can also be a negative number, such as -1,-2,-3... Negative subscripts represent positions in the opposite direction. For example, class_list[-1] returns the last item in class_list.

The sequence not only supports negative subscripts but also double subscripts. This pair of double subscripts represents an interval. For example, class_list[0:3] returns a copy of the subsequence from subscript 1 to subscript 3 in class_list. Note that this interval is a pair of half-closed and half-open intervals. This operation is called a slicing operation. If the second index of the slicing operation exceeds the range of the sequence, the slicing operation will terminate at the end of the sequence. Both subscripts in the slicing operation have default values. The default value of the first is 0, and the size of the second is the length of the sequence.

You can also provide a third parameter for the slicing operation. The third parameter represents the step size of the slicing operation. Its default value is 1. The step size represents the distance between items, such as name[0:10:3]. What is returned is the subsequence composed of subscripts 0, 3, 6, and 9 in name.

5. Set

A collection is an unordered collection of simple objects. Sets are suitable when you only care about whether an object exists in a collection, regardless of the order in which it exists or the number of times it appears. Basic functions: determine whether it is a member of a set, whether a set is a subset of another set, obtain the intersection of two sets, etc. Example:

s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
# 判断对象是否在集合中
if 'Bart' in s:
  print "Bart is in ?", 'Bart' in s
# 使用copy函数来拷贝一个set
sc = s.copy()
# 往集合中添加对象
sc.add('Bill')
# 从集合中删除对象
sc.remove('Adam')
# 求两个集合的交集,也可以使用 s.intersection(sc)
print s & sc
Copy after login

Output result:

Bart is in ? True
set(['Lisa', 'Paul', 'Bart'])
Copy after login

Related recommendations:

Comprehensive analysis of the scope of variables in Python starting from local variables and global variables

The above is the detailed content of Detailed explanation of Python's built-in data structures. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template