内置序列
- list、 tuple 和 collections.deque 这些序列能存放不同类型的数据。
- str、 bytes、 bytearray、 memoryview 和 array.array, 这类序列只能容纳一种类型。
- 容器序列存放的是它们所包含的任意类型的对象的引用, 而扁平序列里存放的是值而不是引用。
- 可变序列: list、 bytearray、 array.array、 collections.deque 和memoryview。
不可变序列: tuple、 str 和 bytes。
列表推到
以前看到过有的 Python 代码用列表推导来重复获取一个函数的副作用。 通常的原则是, 只用列表推导来创建新的列表, 并且尽量保持简短。 如果列表推导的代码超过了两行, 你可能就要考虑是不是得用 for 循环重写了。
>>> symbols = '$¢£¥€¤'
>>> codes = [ord(symbol) for symbol in symbols]
>>> codes
[36, 162, 163, 165, 8364, 164]
变量泄露:
python3.x中实例, python2.x中x=67
>>> x = 'ABC'
>>> dummy = [ord(x) for x in x]
>>> x
'ABC'
>>> dummy
[65, 66, 67]
用生成器表达式初始化元组和数组:
>>> symbols = '$¢£¥€¤'
>>> tuple(ord(symbol) for symbol in symbols) ➊
(36, 162, 163, 165, 8364, 164)
>>> import array
>>> array.array('I', (ord(symbol) for symbol in symbols)) ➋
array('I', [36, 162, 163, 165, 8364, 164])
➊ 如果生成器表达式是一个函数调用过程中的唯一参数, 那么不需要
额外再用括号把它围起来。
➋ array 的构造方法需要两个参数, 因此括号是必需的。 array 构造
方法的第一个参数指定了数组中数字的存储方式。 2.9.1 节中有更多关
于数组的详细讨论。
元组
- 交换数值
>>> b, a = a, b
- 还可以用 * 运算符把一个可迭代对象拆开作为函数的参数:
>>> divmod(20, 8)
(2, 4)
>>> t = (20, 8)
>>> divmod(*t)
(2, 4)
>>> quotient, remainder = divmod(*t)
>>> quotient, remainder
(2, 4)
- 用*来处理剩下的元素在 Python 中, 函数用 *args 来获取不确定数量的参数算是一种经典写法了。于是 Python 3 里, 这个概念被扩展到了平行赋值中:
>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2, 3, 4])
-
嵌套拆包
-
具名元组
>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates') ➊
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) ➋
网友评论