一、%r:可替代 %s、%d 等
>>> s = 'abc'
>>> i = 1
>>> '%r is %r' % (s, i)
"'abc' is 1"
>>> '%r is %r' % (i, s)
"1 is 'abc'"
二、元组拆包
- 元组在Python中的作用:不可变的列表;无名称的字段的记录
- 任何可迭代元素均可使用元组拆包
- 用途
- 平行赋值
- *tuple 作为函数参数
>>> from math import hypot
>>> data = (3,4)
>>> hypot(*data)
5.0
- 函数以元组形式返回多个值
- _占位符,*处理剩余元素(可为空)
三、namedtuple
>>> from collections import namedtuple
>>> People = namedtuple('People', 'name sex age')
>>> man = People('wang', 'man', 15)
>>> man
People(name='wang', sex='man', age=15)
>>> man.name
'wang'
>>> data = ('lin', 'woman', 22)
>>> woman = People._make(data)
>>> woman
People(name='lin', sex='woman', age=22)
>>> woman._asdict()
OrderedDict([('name', 'lin'), ('sex', 'woman'), ('age', 22)])
>>> woman._fields
('name', 'sex', 'age')
四、字典推导
In [8]: codes = [(86, "China"),
...: (91, 'India'),
...: (1, 'United States'),
...: (62, 'Indonestia'),
...: (81, 'Japan')
...: ]
In [9]: country_code = {country: code for code,country in codes}
In [10]: country_code
Out[10]: {'China': 86, 'India': 91, 'Indonestia': 62, 'Japan': 81, 'United State
s': 1}