【Python】数据结构

列表的更多特性

  • list.append(x)
    • 在列表的末尾添加一个元素。相当于 a[len(a):] = [x]
  • list.extend(iterable)
    • 使用可迭代对象中的所有元素来扩展列表。相当于 a[len(a):] = iterable
  • list.insert(i, x)
    • 在给定的位置插入一个元素。第一个参数是要插入的元素的索引,所以 a.insert(0, x) 插入列表头部, a.insert(len(a), x) 等同于 a.append(x)
  • list.remove(x)
    • 移除列表中第一个值为 x 的元素。如果没有这样的元素,则抛出 ValueError 异常。
  • list.pop([i])
    • 删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。( 方法签名中 i 两边的方括号表示这个参数是可选的,而不是要你输入方括号。你会在 Python 参考库中经常看到这种表示方法)。
  • list.clear()
    • 移除列表中的所有元素。等价于del a[:]
  • list.index(x[, start[, end]])
    • 返回列表中第一个值为 x 的元素的从零开始的索引。如果没有这样的元素将会抛出 ValueError 异常。可选参数 start 和 end 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。
  • list.count(x)
    • 返回元素 x 在列表中出现的次数。
  • list.sort(key=None, reverse=False)
    • 对列表中的元素进行排序(参数可用于自定义排序,解释请参见 sorted())。
  • list.reverse()
    • 翻转列表中的元素。
  • list.copy()
    • 返回列表的一个浅拷贝,等价于 a[:]。

列表作为栈使用

入栈:stack.append(x)

出栈:stack.pop()

列表作为队列来使用

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

列表推导式

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

等价于

squares = list(map(lambda x: x**2, range(10)))

或者

squares = [x**2 for x in range(10)]

再来个例子

[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

等价于

combs = []
for x in [1,2,3]:
     for y in [3,1,4]:
         if x != y:
             combs.append((x, y))

forif 的顺序是相同的。

嵌套的列表推导式

matrix = [
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],
 ]

print([[row[i] for row in matrix] for i in range(4)])

或使用内置函数list(zip(*matrix))


元组和序列

一个元组由几个被逗号隔开的值组成

元组是 immutable


集合

花括号 { } 或 set() 函数可以用来创建集合

注意:要创建一个空集合你只能用 set() 而不能用 {},因为后者是创建一个空字典

集合操作

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

集合也可以用推导式

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

字典

创建空字典 {}

删除键值对 del

返回所有字典中的键的列表 list(d)

排序 sorted(d)

检查字典中是否存在特定键,可使用 in 关键字

三种创建字典的方法

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

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

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

循环的技巧

items() 方法可将关键字和对应的值同时取出

enumerate() 函数可以将索引位置和其对应的值同时取出

zip() 函数将其内元素一一匹配。

reversed() 逆序函数

sorted() 排序函数


比较序列和其他类型

使用字典顺序进行比较

例子

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
posted @ 2020-08-30 20:55  宇NotNull  阅读(146)  评论(0编辑  收藏  举报