作为 pprint 模块的替代方案(json.dumps)
# `dict` 的标准字符串 `repr` 很难阅读:
>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430. 'a': 23} # 😞
# `json` 模块可以做的更好 indent 表示空几个空格、sort_keys 表示排序 key
>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
"a": 23,
"b": 42,
"c": 12648430
}
如何合并俩个字典
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}
>>> z = {**x, **y}
>>> z
{'c': 4, 'a': 1, 'b': 3} # 在 Python 2.x ,你可以这样做
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}
is VS ==
>>> a = [1, 2, 3]
>>> b = a
>>> a is b
True
>>> a == b
True
>>> c = list(a)
>>> a == c
True
>>> a is c
False
# is 如果俩个变量点指向统一对象则为真
# == 如果俩个变量值相等则为真
如何根据值对 dict 进行排序
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or:
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
命名元组
# 手动定义类
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4
>>> my_car
Car(color='red' , mileage=3812.4)
# 像元组一样,命名元组是不可变的
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"
变量交换
a = 23
b = 42
# python 可以这样做,变量交换
a, b = b, a
迭代多个序列
a = [1, 2, 3]
b = [4, 5, 6]
for item in a:
...
for item in b:
...
# python 可以这样做
from itertools import chain # chain 里面可以放置多个序列
for item in chain(a, b):
print(item)