Python学习笔记——元组拆包

Python学习笔记——元组拆包


平行赋值:

>>> lax_coordinates = (33.9425, -118.408056)
>>> latitude, longitude = lax_coordinates # 元组拆包
>>> latitude
33.9425
>>> longitude
-118.408056

不使用中间变量交换两个变量的值:

>>> 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])
>>> a, b, *rest = range(3)
>>> a, b, rest
(0, 1, [2])
>>> a, b, *rest = range(2)
>>> a, b, rest
(0, 1, [])
#在平行赋值中,* 前缀只能用在一个变量名前面,但是这个变量可以出现在赋值表达式的任意位置
>>> a, *body, c, d = range(5)
>>> a, body, c, d
(0, [1, 2], 3, 4)
>>> *head, b, c, d = range(5)
>>> head, b, c, d
([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))>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722,
139.691667))
>>> tokyo.population ➌
36.933
>>> tokyo.coordinates
(35.689722, 139.691667)
>>> tokyo[1]
'JP'
#➊ 创建一个具名元组需要两个参数,一个是类名,另一个是类的各个字段的名字。后者可
#以是由数个字符串组成的可迭代对象,或者是由空格分隔开的字段名组成的字符串。
#➋ 存放在对应字段里的数据要以一串参数的形式传入到构造函数中(注意,元组的构造函
#数却只接受单一的可迭代对象)。
#➌ 你可以通过字段名或者位置来获取一个字段的信息。

具名元组的属性和方法:

>>> City._fields ➊
('name', 'country', 'population', 'coordinates')
>>> LatLong = namedtuple('LatLong', 'lat long')
>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
>>> delhi = City._make(delhi_data)>>> delhi._asdict() ➌
OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population',
21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))])
>>> for key, value in delhi._asdict().items():
print(key + ':', value)
name: Delhi NCR
country: IN
population: 21.935
coordinates: LatLong(lat=28.613889, long=77.208889)
#➊ _fields 属性是一个包含这个类所有字段名称的元组。
#➋ 用_make() 通过接受一个可迭代对象来生成这个类的一个实例, 它的作用跟
#City(*delhi_data) 是一样的。
#➌ _asdict() 把具名元组以collections.OrderedDict 的形式返回,我们可以利用它来把元
#组里的信息友好地呈现出来。

参考:流畅的Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值