python 堆、队列操作、字符串格式化输出、字符串常用函数 示例代码

"""
    Created by cheng star at 2018/3/25 13:40
    @email : xxcheng0708@163.com
"""
import heapq
import queue
import random
import collections
from collections import deque
import sys
import timeit
import string

"""
    python 高级数据结构
"""

def test_heap() :
    """
        堆使用
    :return:
    """
    print("run function >>>>>> {0}".format(sys._getframe().f_code.co_name))
    print("####################### heappush 建堆 ########################")
    data = [x for x in range(10)]    # 创建一个数据序列
    data_choice = random.choice(data)   # random 从数据序列中随机选择一个元素
    print(data_choice)
    random.shuffle(data)    # random.shuffle(data) 打乱序列元素顺序关系
    print(data)

    """
        大根堆:每个父节点都大于子节点
        小根队:每个父节点都小于子节点
    """
    heap = []   # 创建一个堆
    for x in data :
        heapq.heappush(heap , x)    # 数据入堆操作
    print(heap)
    heapq.heappush(heap , 0.5)
    print(heap)

    data_pop = heapq.heappop(heap)  # 弹出堆的根,其余节点进行自动建堆
    print(data_pop)
    print(heap)
    data_pop = heapq.heappop(heap)
    print(data_pop)
    print(heap)

    """
        使用序列直接建堆 , heapify
    """
    print("####################### heapify 建堆 ########################")
    data_heap = [x for x in range(10)]
    random.shuffle(data_heap)   # 就地混乱
    heapq.heapify(data_heap)    # 返回None
    print(data_heap)

    data_replace = heapq.heapreplace(data_heap , 5) # 返回堆根元素,并将新元素替换为根元素,重新建堆
    print(data_replace)
    print(data_heap)

    heap_nlargest = heapq.nlargest(3 , data_heap) # 返回堆中前 n 大的元素
    print(heap_nlargest)

    heap_nsmallest = heapq.nsmallest(3 , data_heap) # 返回堆中前 n 小的元素
    print(heap_nsmallest)

def test_queue() :
    """
        队列使用
    :return:
    """
    print("run function >>>>>> {0}".format(sys._getframe().f_code.co_name))
    print("####################### FIFO 队列 #####################")
    q = queue.Queue()   # 创建FIFO队列
    q.put(0)    # 队列中添加元素
    q.put(2)
    q.put(1)
    print(q.queue)

    q_get = q.get() # 队列中获取元素
    print(q_get)
    print(q.queue)

    print("####################### LIFO 队列(栈) #####################")
    q = queue.LifoQueue()   # 创建LIFO队列(后进先出 -> Stack 栈)
    q.put(0)
    q.put(2)
    q.put(1)
    print(q.queue)
    q_get = q.get()
    print(q_get)
    print(q.queue)

    print("####################### PriorityQueue 优先级队列 #####################")
    q = queue.PriorityQueue(5)  # 创建优先级队列,并设置队列最大长度
    q.put(3)
    q.put(2)
    q.put(4)
    q.put(1)
    q.put(5)
    print(q.queue)
    q_get= q.get()
    print(q_get)
    print(q.queue)

    print("####################### collections.deque 双端队列 #####################")
    dq = deque()    # 创建双端队列
    dq.append("zhao")   # 队列右端添加元素
    dq.append("qian")
    dq.append("sun")
    dq.append("li")
    dq.append("cheng")
    dq.appendleft("wang")   # 队列左端添加元素
    dq.appendleft("jiji")
    print(dq)

    pop_left = dq.popleft() # 弹出队列左端元素
    print(pop_left)
    print(dq)
    pop_right = dq.pop()    # 弹出队列右端元素
    print(pop_right)
    print(dq)

def test_zip() :
    """
        zip 函数的使用
    :return:
    """
    print("run function >>>>>> {0}".format(sys._getframe().f_code.co_name))
    l_1 = [x for x in range(10)]
    l_2=  [x for x in range(8)]
    l_zip = zip(l_1 , l_2)  # 用于将多个序列组合成元组序列,以长度最短的为准

    for(k, v) in l_zip :
        print("k = {0} , v = {1}".format(k , v))    # 字符串格式化输出
    # print(l_zip)

def test_str_format() :
    """
        字符串格式化
    :return:
    """
    num = 123
    print("%+d" %num)   # 整数前面添加正号
    print("%o" %num)    # 转换文八进制
    print("%x" %num)    # 转换为十六进制
    print("%e" %num)    # 转换为指数形式

    print("######################## 字符串 format #######################")
    # 使用 {index} 索引位置格式化输出字符串
    print("The number {0:,} in hex is : {0:#x} , the number {1} in oct is {1:#o}".format(5555 , 55))
    print("The number {1} in hex is : {1:#x} , the number {0} in oct is {0:#o}".format(5555 , 55))
    # 使用 {keyword} 关键字参数格式化输出字符串
    print("my nameis {name} ,  my age is {age} , my number is {number}".format(name = "star" , number = "10222953" , age = 26))

    position = [1 , 2 , 3]
    print("X : {0[0]} , Y : {0[1]} , Z : {0[2]}".format(position))

    weather = [("Monday" , "rain") ,
               ("Tuesday" , "sunny") ,
               ("Wednesday" , "sunny") ,
               ("Thursday" , "rain") ,
               ("Frifay" , "cloud")]
    formatter = "Weather of {0[0]} is {0[1]}".format
    """
        help(map) => map(func , *iterables)
    """
    for item in map(formatter , weather) :
        print(item)

def test_str() :
    """
        字符串常用方法
    :return:
    """
    s = "apple,peach,banana,peach,pear"

    print("######################## 字符串查找 #######################")
    print(s.find("peach"))  # 从字符串开始位置开始查找,返回字符串开始位置
    print(s.find("peach" , 7))  # 从 index 指定位置开始查找执行字符串,返回字符串开始位置
    print(s.find("peach" , 7 , 20)) # 在指定的开始位置和结束位置之间查找指定字符串,返回字符串的开始位置
    print(s.rfind("peach")) # 从字符串的右端(尾部)开始查找指定字符串
    print(s.index("bana"))  # 返回字符串厚此出现的位置
    print(s.rindex("bana")) # 从字符串右端(尾部)开始向前,返回字符串首次出现的位置
    print(s.count("p")) # 统计字符串出现次数
    print(s.count("apple"))
    print(s.count("ppp"))

    print("########################### 字符串分割 ########################")
    s_split = s.split(",")  # 从字符串左端开始,按照指定字符串进行分割 split() 默认使用任何空白符号作为分隔符,包括(空格、换行符,制表符)
    print(s_split)
    s_rsplit = s.rsplit(",")    # 从字符串右端开始,按照指定字符串进行分割
    print(s_rsplit)
    s_split_max = s.split("," , 2)  # 指定最大分割次数
    print(s_split_max)

    s_partition = s.partition("banana") # 以指定字符串为分隔符,从字符串左边将源字符串分成三部分,<左边,分隔符,右边>
    print(s_partition)
    s_rpartition = s.rpartition("banana")   # 以指定字符串为分隔符,从字符串右边开始将源字符串分成三部分,<左边,分隔符,右边>
    print(s_rpartition)
    s_partition_none = s.partition("none")  # 如果分隔符不存在,则返回 <源字符串,"" , "">
    print(s_partition_none)

    print("########################### 字符串大小写转换 ########################")
    s = "today is a NICE day !!!"
    print(s.lower())    # 将字符串转换为小写
    print(s.upper())    # 将字符串转换为大写
    print(s.capitalize())   # 将字符串首字母转换为大写,其余转换为小写
    print(s.title())    #将字符串二米个单词的首字母变为大写
    print(s.swapcase()) #字符串中大小写转换

    print("########################### 字符串替换 ########################")
    print(s.replace("today" , "tomorrow"))  # 字符串替换操作,将字符串中的所有str1 替换为str2
    s = "today is a nice day !!! \n tomorrow is rain !!!"
    print(s.replace("\n" , "")) # 替换字符串中的换行符

    print("########################### 字符串映射 ########################")
    s = "python is a great programming language . I like it !!!"
    print(s)
    table = ''.maketrans("abcdef123" , "uvwxyz@#$") # 将str1 中各字符与str2 中各字符建立映射关系
    s_trans = s.translate(table)    # 字符串映射关系
    print(s_trans)

    s = "678"
    s_trans = s.translate(table)    # 如果没有匹配的字符,则返回原字符串
    print(s_trans)

    print("########################### 去除字符串两端空格 ########################")
    s = " python "
    print("start{0}end".format(s.strip()))  # 去除字符串左右两端的空格
    print("start{0}end".format(s.lstrip())) # 去除字符串左端的空格
    print("start{0}end".format(s.rstrip()))   # 去除字符串右端的空格

    print("########################### 判断字符串开始结束startswith/endswith ########################")
    s = "today is a nice day !!!"
    print(s.startswith("today"))    # 从字符串开始位置进行判断
    print(s.startswith("is" , 6))   # 从index执行位置开始判断
    print(s.startswith("today" , 0 , 3))    # 在开始和结束位置区间内进行判断

    print(s.endswith("!!!"))    # 判断字符串以XXX结束
    s1 = "abc"
    s2 = "bcd"
    s3 = "efg"
    print(s1.endswith(("abc" , "bcd" , "efg")))
    print(s2.endswith(("abc" , "bcd" , "efg")))
    print(s3.endswith(("abc" , "bcd" , "efg")))

    print("########################### 判断字符串是否为字母、数字、大小写、空白等 ########################")
    s_num = "123abc"
    s_alp = "abc"
    s_digit = "123"
    s_space = "      "
    s_upper = "ABCDE"
    s_lower = "abcd"
    print(s_num.isalnum())  # 判断字符串是否由字母和数字组成
    print(s_alp.isalpha())  # 判断字符串是否由字母组成
    print(s_digit.isdigit())    # 判断字符串是否由数字组成
    print(s_space.isspace())    # 判断字符串是否由空格组成
    print(s_upper.isupper())    # 判断字符串是否由大写字母组成
    print(s_lower.islower())    # 判断字符串是否由小写字母组成

    print("########################### 获取指定长度的字符串(长度不够自动补齐) ########################")
    s = "Hello , Python"
    print(s.center(20)) # 返回指定长度的字符串,默认两端补齐空格
    print(s.center(20 , "="))   # 返回指定长度的字符串,源字符串居中,两端补齐指定字符
    print(s.ljust(20 , "="))    # 返回执行长度的字符串,源字符串左对齐,右端补齐指定字符
    print(s.rjust(20 , "="))    # 返回指定长度的字符串,源字符串右对齐,左端补齐指定字符

    print("########################### 字符串常量 ########################")
    print(string.digits)    # 数字字符常量
    print(string.ascii_letters) # 英文字母常量
    print(string.punctuation)   # 标点符号常量
    print(string.ascii_lowercase)   # 小写字母常量
    print(string.ascii_uppercase)   # 大写字母常量
    print(string.printable) # 可打印字符常量

def generate_random_string() :
    """
        生成指定长度的随机字符串
    :return:
    """
    # 生成随机长度的随机字符串
    x = "".join([string.digits , string.ascii_lowercase , string.ascii_uppercase , string.punctuation])
    random_count = random.randint(1 , len(x))
    print(random_count)
    random_str = "".join([random.choice(x) for i in range(random_count)])
    print(random_str)

def test_timeit() :
    """
        测试函数执行时间
    :return:
    """
    times = 1000
    print(timeit.timeit("'-'.join(str(n) for n in range(100))" , number = times))
    print(timeit.timeit("'-'.join(map(str , range(100)))" , number = times))    # map 效率更高

if __name__ == "__main__" :
    test_heap()
    test_queue()
    test_zip()
    test_str_format()
    test_str()
    test_timeit()
    generate_random_string()

参考文档:Python程序设计基础 董付国编著 清华大学出版社
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值