5. 数据结构

1、列表方法

list.append(x)

list.extend(L)

list.insert(i, x)

list.remove(x)

list.pop([i])

list.index(x)

list.count(x)

list.sort()

list.reverse()

1.2、列表推导式

列表推导式为从序列中创建列表提供了一个简单的方法。

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

​ 这也相当于squares = map(lambda x: x**2, range(10)), 但是上面的方式显得简洁以及具有可读性。

​ 列表推导式由包含一个表达式的括号组成,表达式后面跟随一个for 子句,之后可以有零或多个for 或if 子句。结果是一个列表,由表达式依据其后面的for 和if 子句上下文计算而来的结果构成。

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

如果想要得到一个元组,必须要加上括号。

>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in ?
	[x, x**2 for x in range(6)]
  SyntaxError: invalid syntax

交换行列,嵌套的列表推导式:

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

## 等价于
>>> transposed = []
>>> for i in range(4):
... 	transposed.append([row[i] for row in matrix])

2、元组和序列

一个元组由数个逗号分隔的值组成

>>> t = 12345, 54321, ’hello!’
>>> t[0]
12345
>>> t
(12345, 54321, ’hello!’)
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, ’hello!’), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
	File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

一个特殊的问题是构造包含零个或一个元素的元组

  • 一对空的括号可以创建空元组;
  • 要创建一个单元素元组可以在值后面跟一个逗号(在括号中放入一个单值不够明确)
# 元组封装
t = 12345, 54321, 'hello!'
# 序列拆封
x, y, z = t

这个调用等号右边可以是任何线性序列,序列拆封要求左侧的变量数目与序列的元组个数相同。

可变参数只是元组封装和序列拆封的一个结合

3、集合

set,集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。集合对象还支持union(联合),intersection(交),difference(差)和sysmmetric difference(对称差集)等数
学运算。

大括号或set()函数可以用来创建集合;

注意:创建空集合,必须使用set()而不是{ },后者用于创建空字典。

>>> basket = {’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’}
>>> print(basket) # show that duplicates have been removed
{’orange’, ’banana’, ’pear’, ’apple’}
>>> ’orange’ in basket # fast membership testing
True
>>> ’crabgrass’
False

4、字典

序列以连续的整数为索引,字典为关键字为索引,关键字可以是任意不可变类型,通常是字符串或数组。

  • 如果元组只包含字符串和数字,它可以作为关键字,如果它直接或间接包含了可变对象,就不能当做关键字。
  • 不能用链表做关键字,因为链表可以用索引、切割或append()和extend()等方法改变。

理解字典的最佳方式是把它看做无序的键:值对(key:value 对)集合,键必须是互不相同的(在同一个字典之内)。一对大括号创建一个空的字典: {} 。初始化链表时,在大括号内放置一组逗号分隔的键:值对,这也是字典输出的方式。

对一个字典执行list(d.keys()) 将返回一个字典中所有关键字组成的无序列表

>>> 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

dect()构造函数可以直接从key-value对中创建字典:

>>> 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}
# 如果关键字都是简单的字符串,有时通过关键字参数指定key-value对更为方便:
>>> dict(sape=4139, guido=4127, jack=4098)
{’sape’: 4139, ’jack’: 4098, ’guido’: 4127}

4.1、循环

  • 在字典循环中,关键字和对应的值可以使用iteritems()方法同时解读出来。
>>> knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
  • 在序列循环中,索引位置和对应值可以使用enumerate()函数同时得到。
>>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):
... 	print(i, v)
...
0 tic
1 tac
2 toe
  • 同时循环两个或更多的序列,可以使用zip()整体打包。
>>> questions = [’name’, ’quest’, ’favorite color’]
>>> answers = [’lancelot’, ’the holy grail’, ’blue’]
>>> for q, a in zip(questions, answers):
... 	print(’What is your {0}? It is {1}.’.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
  • 需要逆向循环序列的话,先正向定位序列,然后调用reversed()函数。
>>> for i in reversed(range(1, 10, 2)):
... 	print(i)
  • 要按排序后的顺序循环序列的话,使用sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列。
原文地址:https://www.cnblogs.com/BigMario/p/13577484.html