一些python练习

一、拾色器

from haishoku.haishoku import Haishoku

image=''#请在此处填入路径~
Haishoku.showPalette(image)
palette=Haishoku.getPalette(image)
for p,rgb in palette:
    hexcolor=f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'
    print(f'{p:.2%}',rgb,hexcolor)

二、批量替换容器中字符串的某个字母

用replace,参数为(旧,新,替换次数)。替换次数为可选参数。代码中字典给了几种写法。

#列表
A = ["a", "bcd", "acd", "cde"]
for i, val in enumerate(A):
    A[i] = val.replace('c', 'x').replace('e', 'y')
print(A)
#元组
B = ("a", "bcd", "acd", "cde")
B = list(B)
for i, val in enumerate(B):
    B[i] = val.replace('c', 'x').replace('e', 'y')
B = tuple(B)
print(B)
#集合
C = {"a", "bcd", "acd", "cde"}
C = {val.replace('c', 'x').replace('e', 'y') for val in C}
print(C)
#字典
D = {'a': "bcd", 'b': "acd", 'c': "cde"}
for key in D:
    D[key] = D[key].replace('c', 'x').replace('e', 'y')
print(D)
#字典
E = {'a': "bcd", 'b': "acd", 'c': "cde"}
for K,V in V.items():
    V=V.replace('c', 'x')
    V=V.replace('e', 'y')
    E[K]=V
print(E)
#字典
F = {'a': "bcd", 'b': "acd", 'c': "cde"}
RE= {'c': "x", 'e': "y"}
for i in RE:
    for K,V in F.items():
        V=V.replace(i,RE[i])
        F[K]=V
print(F)

三、容器嵌套的合法性检查

列表的底层实现:链表结构,动态,栈或队列但不是链表。速度快,内存浪费多,占空间多。

元组的底层实现:链表结构,静态。

集合的底层实现:哈希表。带空值。

字典的底层实现:哈希表(关联表、散列表),通过哈希函数将数据映射到指定内存空间。速度慢,内存浪费少,占空间少。与列表比是空间换时间。

列表的属性:有序,可变,可重复,元素类型可多种

元组的属性:有序,不可变,可重复,元素类型可多种(当元组内嵌套可变类型时,改变的是引用而不是对象本身因此不可变,当然语法还是不合法的)

集合的属性:无序,可变,不可重复,元素类型可多种(set集合可变,frozenset集合不可变)

字典的属性:无序,可变,可重复,元素类型可多种(键必须是可哈希但不可变的串、数、元组)。

数组的属性:有序,可变,可重复,元素类型不可多种(原生python无数组)

其他集合类型:namedtuple:元组子类工厂函数。deque双端队列。counter字典子类可哈希对象计数器。chainmap字典类。ordereddict字典子类可保存添加顺序。defaultdict可设缺失值的字典子类。

x='a',print(type(x))
y=1,print(type(y))
z='我',print(type(z))
#列表
#列表嵌套列表
a=[x,[y,z]],print(type(a))
#列表嵌套元组
b=[x,(y,z,)],print(type(b))
#列表嵌套集合
c=[x,{y,z}],print(type(c))
#列表嵌套字典
d=[x,{y:z}],print(type(d))
#元组:由于元组是不可改的,那么嵌套且改变内部元素,会出现一些奇怪的错误。但貌似可以修改成功。与底层相关。
#元组嵌套列表
e=(x,[y,z],),print(type(e))
#元组嵌套元组
f=(x,(y,z,),),print(type(f))
#元组嵌套集合
g=(x,{y,z},),print(type(g))
#元组嵌套字典
h=(x,{y:z}),print(type(h))
#集合
#集合嵌套列表,报错:TypeError: unhashable type: 'list'
#i={x,[y,z]},print(type(i))
#集合嵌套元组
j={x,(y,z,)},print(type(j))
#集合嵌套集合,报错:TypeError: unhashable type: 'set'
#k={x,{y,z}},print(type(k))
#集合嵌套字典,报错:TypeError: unhashable type: 'dict'
#l={x,{y:z}},print(type(l))
#字典
#字典嵌套列表,报错:TypeError: unhashable type: 'list'
#m={[x]:[y,z]},print(type(m))
#字典嵌套元组
n={x:(y,z,)},print(type(n))
#字典嵌套集合,报错:TypeError: unhashable type: 'set'
#o={{x}:{y,z}},print(type(o))
#字典嵌套字典,报错:TypeError: unhashable type: 'dict'
#p={{x:y}:{y:z}},print(type(p))

四、pandas库提供的数据类型

pandas库提供了两种数组数据类型,Series可视为一维数组,DataFrame可视为二维数组。以前还有Panel类型可视为三维数组。

Series(系列、数列):像字典但不是字典,因为它有序、键可变、提供大量统计方法。

DataFrame(数据帧、数据框)

五、字节码

即CPython解释器出来的内容。

import dis

str=''
def test(arg):
    str='idi10t'
    print(arg,str)
dis.dis(test)

'''
输出
  6           0 LOAD_CONST               1 ('idi10t')
              2 STORE_FAST               1 (str)  

  7           4 LOAD_GLOBAL              0 (print)
              6 LOAD_FAST                0 (arg)  
              8 LOAD_FAST                1 (str)  
             10 CALL_FUNCTION            2        
             12 POP_TOP
             14 LOAD_CONST               0 (None) 
             16 RETURN_VALUE

'''

六、老鼠试药

代码来自网络。

"""
  有100瓶药,只有1瓶是有毒的,老鼠吃完药后,需要3天才能生效,
  现在需要3天知道哪一瓶药有毒,至少需要多少只老鼠
"""
"""
  思考:老鼠喝药有两种状态,生(0) 或 死(1)
        这边时间问题未加上,如果6天或8天,该如何来算老鼠的数量(前3天试药的老鼠如果未死,应该可以复用)
        对于getdiepoison根据死老鼠获取毒药编号的返回值,最后要减1,与我预想的值差1,手动加的,不理解
"""
 
 
class MouseAndPoison(object):
    """
    有100瓶药,只有1瓶是有毒的,老鼠吃完药后,需要3天才能生效,
    现在需要3天知道哪一瓶药有毒,至少需要多少只老鼠
    """
 
    def __init__(self, countpoison, days=3):
        self.countpoison = countpoison
        self.days = days
 
    def getlessmousenum(self):
        """根据毒药的数量判断需要多少只老鼠(老鼠只有两种状态,生或死)"""
        from math import log, ceil
        return ceil(log(self.countpoison, 2))
 
    def poisonbinnum(self):
        """根据需要老鼠的数量和药的数量,将药编号并转成二进制格式,返回药二进制列表"""
        poisonlistbin = []
        for i in range(1, self.countpoison + 1):
            pbinnum = bin(i).replace("0b", "")
            if len(pbinnum) <= self.getlessmousenum():
                pbinnum = ((self.getlessmousenum() - len(pbinnum)) * "0") + pbinnum
            poisonlistbin.append(pbinnum)
        return poisonlistbin
 
    def mouseeatpoison(self):
        """根据药的二进制编号,判断老鼠所需要吃那些药才能查出毒药"""
        mouseeatnub = {}
        for d in list(range(0, self.getlessmousenum())):
            mousepoison = []
            for index, poisonbin in enumerate(self.poisonbinnum()):
                needeatpoison = list(poisonbin)[d]
                if needeatpoison != "0":
                    mousepoison.append(index)
            mouseeatnub[d] = mousepoison
        return mouseeatnub
 
    def getdiemouse(self, poisondienum):
        """根据给出有毒的药,得到那些老鼠会因为毒药而死"""
        mousedielist = []
        for k, v in self.mouseeatpoison().items():
            if poisondienum in v:
                mousedielist.append(k)
        return mousedielist
 
    def getdiepoison(self, diemouse):
        """根据给出死掉的老鼠,得出毒药的编号"""
        n = len(self.mouseeatpoison())
        poisonnumstart = list("0" * n)
        for i in diemouse:
            try:
                mousenum = int(i)
                poisonnumstart[mousenum] = "1"
            except:
                print("err")
        return int("0b" + "".join(poisonnumstart), 2) - 1
 
 
if __name__ == '__main__':
    posionnum = 6
    # 根据药数得到最多需要多少只老鼠
    mouse = MouseAndPoison(posionnum)
    countmouse = mouse.getlessmousenum()
    print(countmouse)
 
    # 根据毒药的编号,判定死了那几只老鼠
    poisondienum = 2
    silaoshu = mouse.getdiemouse(poisondienum)
    print(silaoshu)
 
    # 根据死了那几只老鼠判定毒药编号是多少
    # silaoshu = [4]
    duyao = mouse.getdiepoison(silaoshu)
    print(duyao)

七、解包

# 解包
a, b, *c = [1, 2, 3, 4, 5] 

# a等于1,b等于2,c等于[3, 4, 5]
# 将列表[1, 2, 3, 4, 5]的前两个元素分别赋值给a和b,剩余的元素用*c解包后赋值给c

八、正则分割数字和字母

在以上代码中,我们首先导入了Python中的re模块,用于进行正则表达式操作。然后我们定义了需要处理的字符串input_str,其中包含了字母和数字混合在一起的情况。接下来,我们使用re.sub函数来进行正则表达式替换操作。具体地,我们使用了两个正则表达式,第一个正则表达式会在字母后面的数字前使用下划线隔开,第二个正则表达式会在数字后面的字母前使用下划线隔开。这里使用了r开头的原始字符串,是为了使正则表达式中的反斜杠不被转义。最后,我们输出处理过的字符串output_str。该字符串中,数字和字母之间已经被成功地使用下划线隔开了。

import re
# 需要处理的字符串
input_str = "abc123xy4z"
# 使用正则表达式将数字和字母之间用下划线隔开
output_str = re.sub(r'([a-zA-Z])([0-9])', r'\1_\2', input_str)
output_str = re.sub(r'([0-9])([a-zA-Z])', r'\1_\2', output_str)
# 输出结果
print(output_str)
```

九、截图工具

import tkinter as tk
import pyautogui

class Screenshot:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("200x100")
        self.root.resizable(False, False)
        self.root.title("Screenshot")
        
        self.button1 = tk.Button(self.root, text="截图", command=self.capture)
        self.button1.pack(pady=20, ipadx=5, ipady=5)
        
        self.root.mainloop()
    
    def capture(self):
        # 隐藏当前窗口
        self.root.withdraw()
        
        # 等待一会以保证窗口已被隐藏
        self.root.after(100)
        
        # 截图并保存为“screenshot.png”
        screenshot = pyautogui.screenshot()
        screenshot.save("screenshot.png")
        
        # 显示当前窗口
        self.root.update()
        self.root.deiconify()

if __name__ == '__main__':
    Screenshot()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值