python - python中的30个编程小技巧
2023-09-27 14:29:09 时间
从公众号上看到了一篇文章《30个python编程技巧!》,觉得有些挺有用的,有的也一直在用,就挨个实现了一下。
In [1]:
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
In [3]:
n = 10
print(1 < n < 20)
print(1 > n <= 9)
In [4]:
y = 20
x = 9 if (y == 10) else 8
print(x)
In [6]:
# 找abc中最小的数
def small(a, b, c):
return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))
In [7]:
# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)
In [15]:
multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
In [16]:
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)
In [17]:
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
In [18]:
testList = [1, 2, 3]
x, y, z = testList # 变量个数应该和列表长度严格一致
print(x, y, z)
In [19]:
import threading
import socket
print(threading)
print(socket)
In [1]:
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
In [ ]:
import pdb
pdb.ste_trace()
In [ ]:
python -m http.server
In [3]:
test = [1, 3, 5, 7]
print(dir(test))
In [4]:
test = range(10)
print(dir(test))
In [ ]:
# use following way to verify multi values
if m in [1, 2, 3, 4]:
# do not use following way
if m==1 or m==2 or m==3 or m==4:
In [12]:
import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
print("sorry, you are not running on python 2.7")
print("current python version:", sys.version)
In [19]:
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
In [21]:
# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
In [23]:
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
print(element)
In [24]:
# 翻转字符串
print("Test Python"[::-1])
In [25]:
# 用切片翻转列表
print([1, 3, 5][::-1])
In [26]:
test = [10, 20, 30]
for i, value in enumerate(test):
print(i, ':', value)
In [27]:
class shapes:
circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
In [28]:
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
In [35]:
def test(x, y, z):
print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)
In [37]:
stdcalc = {
"sum": lambda x, y: x + y,
"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
In [38]:
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
In [40]:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
In [41]:
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
In [42]:
import sys
x = 1
print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节
In [47]:
import sys
# 原始类
class FileSystem(object):
def __init__(self, files, folders, devices):
self.files = files
self.folder = folders
self.devices = devices
print(sys.getsizeof(FileSystem))
# 减少内存后
class FileSystem(object):
__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folder = folders
self.devices = devices
print(sys.getsizeof(FileSystem))
In [49]:
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
In [50]:
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
In [52]:
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
In [55]:
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
In [58]:
def xswitch(x):
return xswitch._system_dict.get(x, None)
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))
相关文章
- 【ROS学习笔记】7.订阅者Subscriber的编程实现(C++和Python)
- python对list列表进行排序方法总结
- [ python ] 网络编程(2)
- 【python入门到精通】python函数式编程与应用详解
- Python网络编程中的select 和 poll I/O复用的简单使用
- Python编程:Django自定义模板标签
- Python编程:使用数据库sqlite3
- Python_12-线程编程
- python 爬虫系列07-天气爬虫
- 【工具技巧】PyCharm 中 Python 库(Package)的 Latest version 时常看不到,咋个回事 ?
- 全国青少年软件编程等级考试Python标准解读(1_6级)
- 2022.12青少年软件编程(Python)等级考试试卷(三级)
- 2021.03青少年软件编程(Python)等级考试试卷(三级)
- Python Class 写在编程之前
- 第1章 Python学习环境构建目录
- python编程(类的释放)
- python 编程(编写汽车保养时间表)
- python编程(pdb调试)
- python发送邮件
- Python网络编程基础【底层网络】
- python 获取当前系统4种方法
- 好学编程:Python有哪些优势和用途?学Python就业方向有哪些?
- 盘点Python爬虫中的常见加密算法,建议收藏!!
- Python 正则表达式学习摘要及资料
- Python-函数式编程
- python - RSA的加密和解密
- 十七、python学习之MySQL数据库(四): 数据库编程