前言
对 python 的一些使用经验进行说明整理
- 『python』python基础教程(1) — 基本数据结构
- 『python』python基础教程(2) — 基础知识整理
- 『python』python基础教程(3) — 高阶方法使用
- 『python』python基础教程(4) — 常用操作
一、检查创建的对象占了多少内存
import sys
mylist = [x for x in range(0,10)]
print(sys.getsizeof(mylist))
二、从 list 或是 string 中获取 unique 元素
可以用 set()
来获取 list 或是类似于 list 的对象的 unique 元素,结果返回为一个 set。
mylist = [1, 1, 2, 2, 3, 4, 3, 5, 6, 6]
print(set(mylist)) # {1,2,3,4,5,6}
print(set("aaabbbcccccddefff")) # {'a','b','c','d','e','f'}
三、条件赋值的三元运算符
[on_true] if [expression] else [on_false]
四、统计出现次数
可以使用 collection
库来获得 list 中各个 unique 值的出现,并返回一个 dictionary.
from collections import Counter
mylist = [1,1,2,2,2,3,3,3,3,3,4,4,5,5,5]
c = Counter(mylist)
print(c) # {1:2, 2:3, 3:5, 4:2, 5:3}
print(Counter("aaabbcccc")) # {'a':3, 'b':2, 'c':4}
五、批量压缩文件夹和文件
import zipfile # 导入zipfile,这个是用来做压缩和解压的Python模块;
import os
import time
def batch_zip(start_dir):
start_dir = start_dir # 要压缩的文件夹路径
file_news = start_dir + '.zip'# 压缩后文件夹的名字
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
for dir_path, dir_names, file_names in os.walk(start_dir):
# 这一句很重要,不replace的话,就从根目录开始复制
f_path = dir_path.replace(start_dir, '')
f_path = f_path and f_path + os.sep # 实现当前文件夹以及包含的所有文件的压缩
for filename in file_names:
z.write(os.path.join(dir_path, filename), f_path + filename)
z.close()
return file_news
batch_zip('./data/ziptest')
六、输入数据转换
python3 需要编写接受 str 或 bytes,并总是返回 str 的方法:
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value # Instance of str
接受 str 或 bytes,并总是返回 bytes 的方法:
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value # Instance of bytes