数据结构

2018-05-02  本文已影响17人  Kean_L_C

内置序列

列表推到

以前看到过有的 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)
>>> 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)) ➋

collections.deque

上一篇 下一篇

猜你喜欢

热点阅读