您现在的位置是:主页 > news > 网站建设发展方向/网络软文推广案例

网站建设发展方向/网络软文推广案例

admin2025/6/29 12:20:19news

简介网站建设发展方向,网络软文推广案例,求一个自己做的网站链接,宁波网站建设招聘网文章目录前言一、检查创建的对象占了多少内存二、从 list 或是 string 中获取 unique 元素三、条件赋值的三元运算符四、统计出现次数五、批量压缩文件夹和文件六、输入数据转换前言 对 python 的一些使用经验进行说明整理 『python』python基础教程(1) — 基本数据结构『pytho…

网站建设发展方向,网络软文推广案例,求一个自己做的网站链接,宁波网站建设招聘网文章目录前言一、检查创建的对象占了多少内存二、从 list 或是 string 中获取 unique 元素三、条件赋值的三元运算符四、统计出现次数五、批量压缩文件夹和文件六、输入数据转换前言 对 python 的一些使用经验进行说明整理 『python』python基础教程(1) — 基本数据结构『pytho…

文章目录

  • 前言
  • 一、检查创建的对象占了多少内存
  • 二、从 list 或是 string 中获取 unique 元素
  • 三、条件赋值的三元运算符
  • 四、统计出现次数
  • 五、批量压缩文件夹和文件
  • 六、输入数据转换


前言

对 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 timedef 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_newsbatch_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_strreturn 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_strreturn value    # Instance of bytes