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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章