python小技巧

python小技巧

利用zip将两个可迭代对象生成为字典

keys = ["Bob", "Jack", "Tom", "Mary"]
values = ["male", "male", "male", "female"]

d = dict(zip(keys, values))

通过 * 实现 unpack

In [19]: c = zip(keys, values)
In [20]: a, b = zip(*c)

In [21]: a
Out[21]: ('Bob', 'Jack', 'Tom', 'Mary')

In [22]: b
Out[22]: ('male', 'male', 'male', 'female')

为json.dumps添加参数indent

In [1]: import json

In [2]: a = {"a": 1, "b": 2, "c": {"c": 3}}

In [3]: print(json.dumps(a, indent=2))
{
  "a": 1,
  "b": 2,
  "c": {
    "c": 3
  }
}

运算符优先级

算术运算符 > 比较运算符 > 赋值运算符 > 身份运算符 > 成员运算符 > 逻辑运算符
如果优先级不确定请使用()


临时变量 _

In [8]: a = 1 + 2

In [9]: a
Out[9]: 3

In [10]: _
Out[10]: 3

In [11]: b = 3 + 3

In [12]: b
Out[12]: 6

In [13]: _
Out[13]: 6

In [14]: 4 + 5
Out[14]: 9

In [15]: _
Out[15]: 9

In [16]: _ = 5 + 5

In [17]: _
Out[17]: 10

In [18]: 6 + 6
Out[18]: 12

In [19]: _
Out[19]: 10

参考链接
Python运算符优先级
python 实用的30个小技巧

相关推荐