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
  }
}

運算符優先級

算術運算符 > 比較運算符 > 賦值運算符 > 身份運算符 > 成員運算符 > 邏輯運算符
若是優先級不肯定請使用()html


臨時變量 _

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個小技巧python

相關文章
相關標籤/搜索