Python小技巧

  1. 原地交換兩個變量的值
x, y = 10, 20
print(x, y)
# 10, 20
y, x = x, y
print(x, y)
# 20, 10
  1. 三元運算符

格式: [條件爲真,返回值] if [表達式] else [條件爲假,返回值]

x = 9
y = True if x > 10 else False
print(y)
# False
  1. 引入模塊的絕對路徑
import threading
# 直接print打印
print(threading)
# 結果
# <module 'threading' from '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>
  1. 獲取變量擁有的方法和屬性
alist = [1, 2]
print(dir(alist))
# 結果
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
adict = {"a": 1, "b": 2}
print(dir(adict))
# 結果
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
  1. 檢測Python的版本
import sys
print(sys.version)
# '3.7.1 (default, Nov 28 2018, 11:51:47) \n[Clang 10.0.0 (clang-1000.11.45.5)]'
# 判斷Python版本
if sys.version_info > (3, 0):
  print("當前程序運行的是Python3")
else:
    print("當前程序運行的是Python2")
  1. 開啓一個HTTP服務器,可在局域網內進行文件傳輸/手機讀取電腦文件(同一個WiFi)
# 只有python3 有這個方法
python3 -m http.server 端口號(默認是8000)
# Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
# 瀏覽器訪問本機IP:8000 即可訪問電腦根目錄
# Windows 獲取本機IP 命令: ipconfig
# Mac / Linux 獲取本機IP命令: ifconfig
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章