A brief introduction to the data structure of Python basics

This article mainly introduces Python data structure based on the knowledge points learned previously.

List:

Lists in Python are mutable, which is the most important feature that distinguishes them from strings and tuples. In one sentence, lists can be modified, but strings and tuples cannot.

Here are the methods for lists in Python:

method describe
list.append(x) Adding an element to the end of the list is equivalent to a[len(a):] = [x].
list.extend(L) Extends the list by adding all elements of the specified list, equivalent to a[len(a):] = L.
list.insert(i, x) Inserts an element at the specified position. The first parameter is the index of the element to be inserted before it. For example, a.insert(0, x) will be inserted before the entire list, and a.insert(len(a), x) is equivalent to a.append( x).
list.remove(x) Remove the first element with value x from the list. If there is no such element, an error will be returned.
list.pop([i]) Removes an element from the specified position in the list and returns it. If no index is specified, a.pop() returns the last element. The element is removed from the list. (The square brackets around i in the method indicate that the parameter is optional, rather than requiring you to enter a pair of square brackets. You will often encounter such markings in the Python library reference manual.)
list.clear() Removes all items from the list, equivalent to del a[:].
list.index(x) Returns the index of the first element in the list with value x. If there are no matching elements, an error will be returned.
list.count(x) Returns the number of times x appears in the list.
list.sort() Sort elements in a list.
list.reverse() Arrange the elements in an inverted list.
list.copy() Returns a shallow copy of the list, equal to a[:].

Note: Methods that modify the list such as insert, remove or sort have no return value.

The list method allows the list to be easily used as a stack. The stack is a specific data structure, and the first element entered is the last to be released (last in, first out). Use the append() method to add an element to the top of the stack. An element can be released from the top of the stack using the pop() method without specifying an index. For example:

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack) # [3, 4, 5, 6, 7]

stack.pop() # 7
print(stack) # [3, 4, 5, 6]

stack.pop() # 6

stack.pop() # 5

print(stack) # [3, 4]

You can also use the list as a queue, but the first element added to the queue is the first to be taken out; however, it is not efficient to use the list for such a purpose. Adding or popping elements from the end of the list is fast, but inserting or popping elements from the head of the list is not fast (because all other elements have to be moved one by one).

tuples and sequences

元组由若干逗号分隔的值组成,例如:
t = 12345, 54321, 'hello!'
print(t[0]) # 12345

print(t) # (12345, 54321, 'hello!')

u = t, (1, 2, 3, 4, 5)
print(u) # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

如你所见,元组在输出时总是有括号的,以便于正确表达嵌套结构。在输入时可能有或没有括号, 不过括号通常是必须的(如果元组是更大的表达式的一部分)。

gather

A set is an unordered set of non-repeating elements. Basic functionality includes relationship testing and elimination of duplicate elements.

Collections can be created using curly braces ({}). Note: If you want to create an empty collection, you must use set() instead of {}; the latter creates an empty dictionary. We will introduce this data structure in the next section.

以下是一个简单的演示:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 删除重复的
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 检测成员
True
>>> 'crabgrass' in basket
False

>>> # 以下演示了两个集合的操作
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # a 中唯一的字母
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 在 a 中的字母,但不在 b 中
{'r', 'd', 'b'}
>>> a | b                              # 在 a 或 b 中的字母
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 在 a 和 b 中都有的字母
{'a', 'c'}
>>> a ^ b                              # 在 a 或 b 中的字母,但不同时在 a 和 b 中
{'r', 'd', 'b', 'm', 'z', 'l'}

集合也支持推导式:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

dictionary

Another very useful built-in data type in Python is the dictionary.

Unlike sequences, which are indexed by consecutive integers, dictionaries are indexed by keys, which can be any immutable type, usually strings or numeric values.

The best way to think of a dictionary is as an unordered collection of key => value pairs. Within the same dictionary, keywords must be different from each other.

A pair of braces creates an empty dictionary: {}.

这是一个字典运用的简单例子:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

构造函数 dict() 直接从键值对元组列表中构建字典。如果有固定的模式,列表推导式指定特定的键值对:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
此外,字典推导可以用来创建任意键和值的表达式词典:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

如果关键字只是简单的字符串,使用关键字参数指定键值对有时候更方便:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

It’s not easy to organize, thank you~~

Guess you like

Origin blog.csdn.net/hbblzjy/article/details/121680274
Recommended