『python』python基础教程(5) — 使用经验


前言

对 python 的一些使用经验进行说明整理

  1. 『python』python基础教程(1) — 基本数据结构
  2. 『python』python基础教程(2) — 基础知识整理
  3. 『python』python基础教程(3) — 高阶方法使用
  4. 『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
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

libo-coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值