《流畅的python》学习笔记 - 元组

  元组(tuple)其实就是对数据的记录,元组中每个元素都是数据库表中一个字段的数据,外加这个字段的位置。正是这个位置信息给数据赋予了意义。 尤其是元组的引申变种“具名元组(named tuple)”。
  一定要理解这句话:正是这个位置信息给数据赋予了意义,才能正确的理解元组的“元组拆包”、“平行赋值”、“_占位符”、“*运算符”以及“嵌套元组拆包”。

具名元组

  具名元组(namedtuple)是一个工厂函数,用来构建一个带字段名的元组和一个有名字的类。
  具名元组的定义及使用:

>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667))
>>> tokyo.population
36.933
>>> tokyo[1]
'JP'

元组拆包(可迭代元素拆包)

>>> city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
>>> city
'Tokyo'
>>> year
2003
>>> pop
32450
>>> chg
0.66
>>> area
8014
>>> traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')]
>>> for passport in sorted(traveler_ids):
...     print ('%s / %s' %passport)
... 
BRA / CE342567
ESP / XDA205856
USA / 31195855
>>> for country , _ in traveler_ids:
...     print (country)
... 
USA
BRA
ESP
>>> 

  上面三段代码都是元组拆包的例子,元组拆包适用任何可迭代对象,唯一的要求是:迭代产生的每一个元素都要有对应的变量,除非用“ * ”来表示忽略多余的元素。(原版英文是:Tuple unpacking works with any iterable object. The only requirement is that the iterable yields exactly one item per variable in the receiving tuple, unless you use a star (*) to capture excess items as explained in “Using * to grab excess items” on page 29.)。在阅读中文版时,感觉中文版对应的翻译有歧义,所以找来原版。

平行赋值和‘_’占位符

  参考上面第一段代码和第三段代码。

*运算符

>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2, 3, 4])
>>> a, *rest , b = range(5)
>>> a, rest, b
(0, [1, 2, 3], 4)

  python中,函数用* args来获取不确定数量参数的用法,扩展到平行赋值中,就是*运算符。

嵌套元组拆包

The tuple to receive an expression to unpack can have nested tuples, like (a, b, (c,d)), and Python will do the right thing if the expression matches the nesting structure.
用于拆包的元组可以包含嵌套元组,只要表达式与嵌套结构一致,python就能搞定。

>>> areas = ('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> name, cc, pop, (lat, long) = areas
>>> name, cc,pop, (lat, long)
('Tokyo', 'JP', 36.933, (35.689722, 139.691667))

猜你喜欢

转载自blog.csdn.net/steventian72/article/details/85622428