Python笔记相关(下)

简介: Python笔记相关

Python笔记相关(中):https://developer.aliyun.com/article/1488578


完整版

import pygame, random, sys
from pygame.locals import *
from define import *
# 初始化窗口宽高
WINWIDTH = 640
WINHEIGHT = 480
# 初始化推盘行列和空格
ROW = 3
COL = 3
BLANK = None
# 颜色预设
DARKGRAY = (60, 60, 60)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 193)
GRAY = (128, 128, 128)
BRIGHTBLUE = (138, 228, 221)
# 颜色变量
BLANKCOLOR = DARKGRAY
MSGCOLOR = WHITE
BTCOLOR = YELLOW
BTTEXTCOLOR = GRAY
BDCOLOR = BRIGHTBLUE
# 静态常量
BLOCKSIZE = 80  # 方块大小
FPS = 60  # 帧率
# 按键事件
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
NEWGAME = 'newgame'
# 随机移动次数
AUTOMOVE = random.randint(50, 100)
# 文本对象创建
def makeText(text, tColor, btColor, top, left):
    textSurf = BASICFONT.render(text, True, tColor, btColor)
    textRect = textSurf.get_rect()
    textRect.topleft = (top, left)
    return textSurf, textRect  # 将字体渲染的Surface对象,Surface对象的矩形属性
# 绘制方块在窗口(tilex,tiley)处,adjx与adjy为偏移量,可选参数默认值为0
def drawTile(tilex, tiley, number, adjx=0, adjy=0):
    left, top = getLeftTopOfTile(tilex, tiley)
    # 绘制方块
    pygame.draw.rect(WINSET, BTCOLOR, (left + adjx, top + adjy, BLOCKSIZE, BLOCKSIZE))
    # 将数字number渲染到方块上
    textSurf = BASICFONT.render(str(number), True, BTTEXTCOLOR)
    # 获取矩形属性
    textRect = textSurf.get_rect()
    # print(textRect)
    textRect.center = left + int(BLOCKSIZE / 2) + adjx, top + int(BLOCKSIZE / 2) + adjy
    # print(textRect.center)
    # print(textRect)
    # 绘制到静态窗口上
    WINSET.blit(textSurf, textRect)
# 计算方块左上角 距离窗口原点纵横坐标距离
def getLeftTopOfTile(tilex, tiley):
    # 先计算左上角方块的距离
    xMargin = int((WINWIDTH - (BLOCKSIZE * COL + (COL - 1))) / 2)  # 199
    yMargin = int((WINHEIGHT - (BLOCKSIZE * ROW + (ROW - 1))) / 2)  # 119
    # print(xMargin,yMargin)
    # print(tilex, tiley) ?
    left = xMargin + (tilex * BLOCKSIZE) + (tilex - 1)
    top = yMargin + (tiley * BLOCKSIZE) + (tiley - 1)
    # print(left, top)
    return left, top
# 静态界面绘制
def darwStaticWin():
    winSet = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
    pygame.display.set_caption('数字华容道')
    image = pygame.image.load('bg.jpg')
    winSet.blit(image, (0, 0))
    # 按钮创建
    new_surf, new_rect = makeText('新游戏', BTTEXTCOLOR, BTCOLOR, WINWIDTH - 85, WINHEIGHT - 40)
    winSet.blit(new_surf, new_rect)
    return winSet, new_surf, new_rect
# 动态界面绘制
def drawBoard(board, msg):
    # board 推盘列表
    WINSET.blit(STATICSURF, (0, 0))
    # 如果消息不为空
    if msg:
        msgSurf, msgRect = makeText(msg, MSGCOLOR, None, 5, 5)
        pygame.image.save(msgSurf, 'msg.png')  # 将msgSurf存为名为msg.png的图片
        imgSurf = pygame.image.load('msg.png')  # 加载图片
        # print(msgRect)  # <rect(5, 5, 87, 28)>  矩形属性
        WINSET.blit(imgSurf, msgRect)
    for i in range(len(board)):  # 3
        for j in range(len(board[0])):  # 3
            if board[i][j]:  # 遍历出不为None的
                # print(board[i][j])
                drawTile(i, j, board[i][j])  # 方块上的数字和所在的行列,绘制方块及数字
    # 绘制外边框
    left, top = getLeftTopOfTile(0, 0)  # 198 118
    width = COL * BLOCKSIZE  # 240
    height = ROW * BLOCKSIZE  # 240
    pygame.draw.rect(WINSET, BDCOLOR, (left - 5, top - 5, width + 11, height + 11), 4)  # 外沿厚度4
# 生成推盘序列
def getStartingBoard():
    initBoard = []  # 二维列表
    for i in range(COL):  # 列
        i = i + 1
        column = []
        for j in range(ROW):
            column.append(i)
            i += COL  # 按列添加,非顺序添加
        initBoard.append(column)
    initBoard[ROW - 1][COL - 1] = BLANK  # 最后一位添加None空格
    # print(initBoard)
    return initBoard
# 初始化推盘,随机移动numSlides(50~100)次
def generateNewPuzzle(numSlides):
    mianBoard = getStartingBoard()  # 获取拼图列表
    drawBoard(mianBoard, '')
    lastMove = None
    for i in range(numSlides):
        move = getRandomMove(mianBoard, lastMove)  # 获取随机移动的方向
        slideAnimation(mianBoard, move, '初始化...', int(BLOCKSIZE / 3))
        makeMove(mianBoard, move)
        lastMove = move
    return mianBoard
# 移动交换元素位置
def makeMove(board, move):
    blankx, blanky = getBlankPosition(board)
    if move == UP:
        board[blankx][blanky], board[blankx][blanky + 1] = board[blankx][blanky + 1], board[blankx][blanky]
    elif move == DOWN:
        board[blankx][blanky], board[blankx][blanky - 1] = board[blankx][blanky - 1], board[blankx][blanky]
    elif move == LEFT:
        board[blankx][blanky], board[blankx + 1][blanky] = board[blankx + 1][blanky], board[blankx][blanky]
    elif move == RIGHT:
        board[blankx][blanky], board[blankx - 1][blanky] = board[blankx - 1][blanky], board[blankx][blanky]
# 移动的动画效果
def slideAnimation(board, direction, msg, animationSpeed):
    blankx, blanky = getBlankPosition(board)  # 获取空格的行列坐标
    # 获取被移动的方块所在的行列
    if direction == UP:
        movex = blankx
        movey = blanky + 1
    elif direction == DOWN:
        movex = blankx
        movey = blanky - 1
    elif direction == LEFT:
        movex = blankx + 1
        movey = blanky
    elif direction == RIGHT:
        movex = blankx - 1
        movey = blanky
    drawBoard(board, msg)
    BASESURF = WINSET.copy()  # 复制此刻背景作为Surface对象
    # 绘制空白块
    moveLeft, moveTop = getLeftTopOfTile(movex, movey)
    pygame.draw.rect(BASESURF, BLANKCOLOR, (moveLeft, moveTop, BLOCKSIZE, BLOCKSIZE))
    # 连续绘制被移动的方块
    # print(animationSpeed)  # 26 方块移动速度
    for i in range(0, BLOCKSIZE, animationSpeed):
        checkForQuit()
        WINSET.blit(BASESURF, (0, 0))
        if direction == UP:
            drawTile(movex, movey, board[movex][movey], 0, -i)
        if direction == DOWN:
            drawTile(movex, movey, board[movex][movey], 0, i)
        if direction == LEFT:
            drawTile(movex, movey, board[movex][movey], -i, 0)
        if direction == RIGHT:
            drawTile(movex, movey, board[movex][movey], i, 0)
        pygame.display.update()  # 更新界面
        FPSCLOCK.tick(FPS)  # 控制帧率
# 判断无效移动
def isValidMove(board, direction):
    blankx, blanky = getBlankPosition(board)
    if blankx == 0 and direction == RIGHT:
        return False
    elif blankx == 2 and direction == LEFT:
        return False
    elif blanky == 0 and direction == DOWN:
        return False
    elif blanky == 2 and direction == UP:
        return False
    else:
        return True
# 获取随机移动的方向
def getRandomMove(board, lastMove=None):
    validMoves = [UP, DOWN, LEFT, RIGHT]
    if lastMove == UP or not isValidMove(board, DOWN):
        validMoves.remove(DOWN)
    if lastMove == DOWN or not isValidMove(board, UP):
        validMoves.remove(UP)
    if lastMove == LEFT or not isValidMove(board, RIGHT):
        validMoves.remove(RIGHT)
    if lastMove == RIGHT or not isValidMove(board, LEFT):
        validMoves.remove(LEFT)
    return random.choice(validMoves)
def getBlankPosition(board):
    for x in range(COL):
        for y in range(ROW):
            if board[x][y] == BLANK:
                return (x, y)
def getSpotClicked(board, x, y):
    for tilex in range(len(board)):
        for tiley in range(len(board[0])):
            left, top = getLeftTopOfTile(tilex, tiley)
            tileRect = pygame.Rect(left, top, BLOCKSIZE, BLOCKSIZE)
            if tileRect.collidepoint(x, y):  # 如果产生碰撞
                return tilex, tiley  # 返回行列
    return None, None
# 获取用户输入
def getInput(mainBoard):
    events = pygame.event.get()
    userInput = None
    for event in events:
        if event.type == MOUSEBUTTONUP:
            # 获取位置关系
            spotx, spoty = getSpotClicked(mainBoard, event.pos[0], event.pos[1])
            # 坐标不在拼图区域,点击的新游戏
            if (spotx, spoty) == (None, None) and NEW_RECT.collidepoint(event.pos):
                userInput = NEWGAME
            else:
                # 如果已完成,点击非选项时不移动
                if mainBoard == getStartingBoard():
                    break
                # 点击位置是否在BLANK旁边
                blankx, blanky = getBlankPosition(mainBoard)
                if spotx == blankx + 1 and spoty == blanky:
                    userInput = LEFT  # 设置移动方向
                elif spotx == blankx - 1 and spoty == blanky:
                    userInput = RIGHT
                elif spotx == blankx and spoty == blanky + 1:
                    userInput = UP
                elif spotx == blankx and spoty == blanky - 1:
                    userInput = DOWN
    return userInput
# 对用户输入进行处理
def processing(userInput, mainBoard, msg):
    if mainBoard == getStartingBoard():
        msg = '完成'
    else:
        msg = '通过鼠标移动方块'
    if userInput:
        # 功能按钮  新游戏处理:
        if userInput == NEWGAME:
            getStartingBoard()  # 初始化推盘列表
            mainBoard = generateNewPuzzle(AUTOMOVE)  # 随机次数移动打乱
        else:
            # 方块移动
            slideAnimation(mainBoard, userInput, msg, 8)
            makeMove(mainBoard, userInput)
    return mainBoard, msg
# 资源回收与程序退出
def terminate():
    pygame.quit()  # 模块卸载
    sys.exit()
# 退出判断
def checkForQuit():
    for event in pygame.event.get(QUIT):  # 获取所有可能会导致退出的事件,存在就执行退出
        terminate()  # 执行退出
    for event in pygame.event.get(KEYUP):  # 按下ESC键退出
        if event.key == K_ESCAPE:
            terminate()
        pygame.event.post(event)  # 发送事件至消息列队
def main():
    # FPSCLOCK Clock对象
    # WINSET 窗体Surface对象
    # STATICSURF 静态窗体Surface对象
    # BASICFONT 字体对象
    # NEW_SURF "新游戏"Surface对象,一张内容为文字的图片  调用字体对象的render()方法,渲染为Surface对象显示
    # NEW_RECT get_rect()方法获取的"新游戏"矩形属性
    global FPSCLOCK, WINSET, STATICSURF, BASICFONT  # 定义全局变量
    global NEW_SURF, NEW_RECT
    pygame.init()
    FPSCLOCK = pygame.time.Clock()  # 创建一个Clock对象,并使用变量FPSCLOCK保存
    BASICFONT = pygame.font.Font('STKAITI.TTF', 25)  # 定义返回一个字体对象,并使用变量BASICFONT保存
    WINSET, NEW_SURF, NEW_RECT = darwStaticWin()  # 创建静态窗口
    STATICSURF = WINSET.copy()  # 复制一个静态窗口作为底板
    mainBoard = generateNewPuzzle(AUTOMOVE)  # 初始化列表
    msg = None
    while True:
        FPSCLOCK.tick(FPS)  # 设置帧率
        drawBoard(mainBoard, msg)  # 动态界面绘制
        pygame.display.update()  # 刷新
        checkForQuit()  # 判断是否终止
        userInput = getInput(mainBoard)  # 获取输入
        mainBoard, msg = processing(userInput, mainBoard, msg)  # 输入处理
if __name__ == '__main__':
    main()

总结


只一个函数没给出,作用是判断无效移动


错误原因:

错误判断了行与列,blankx代表列,blanky代表行;且0为第一行,2为最后一行

# 判断无效移动
def isValidMove(board, direction):
    blankx, blanky = getBlankPosition(board)
    if blankx == 0 and direction == RIGHT:
        return False
    elif blankx == 2 and direction == LEFT:
        return False
    elif blanky == 0 and direction == DOWN:
        return False
    elif blanky == 2 and direction == UP:
        return False
    else:
        return True

错误排查


1、TypeError:darwStaticWin()缺少两个必需的位置参数:“BTTEXTCOLOR”和“BTCOLOR”

2、(<class‘TypeError’>,TypeError(‘isValidMove()接受0个位置参数,但给出了2个’),<位于0x000002312E0D7740的回溯对象‘)。

3、(<class‘IndexError’>,IndexError(‘列出索引超出范围’),<traceback object at 0x000001478DB88800>)。

4、TypeError:DrawBoard()缺少1个必需的位置参数:‘msg’

5、Unbound LocalError:赋值前引用的局部变量‘event’

6、IndexError: list index out of range


实现思路


1、

整个游戏以MVC的设计模式进行设计,采用自顶向下的方式,将总问题逐渐向下分层,直到分为一个一个能被解决的小问题,实现整个游戏。

将游戏分为Model(模型层)-View(视图层)-Controller(控制层),分层级一层一层去实现,将大问题分割为小问题。

2、Model

model部分应实现的推盘序列的生成与存储,

  • getStartingBoard函数,根据行列生成一个二级列表,返回 initBoard ,表示的是初始的二级列表顺序,可用于判断游戏是否完成。
  • makeMove函数,接收列表和移动方向两个参数,将交换位置后的序列存储,不返回结果。一般与移动的动画效果函数slideAnimation 一起使用,每次移动之后将序列存储一次。应该可以写在一起,待尝试。
3、View

view部分负责视图的显示,包括有提示信息msg、推盘方块、外边框、按钮等。

  • 首先是 darwStaticWin 函数,用于创建窗口以及设置窗口标题、背景、图片、文字显示等。由于经常会使用到绘制文字显示,为了代码复用,精简代码,将其封装为一个函数makeText,提供要绘制的文本、文字颜色、背景色、绘制位置等参数,返回一个Surface对象与其矩形属性<rect(555, 440, 75, 28)>,分别表示距离y轴的距离、距离x轴的距离、矩形的长和高。共有两处使用,体会其使用。
  • 按钮的实质,其实就是一个带背景色的文字显示。
new_surf, new_rect = makeText('新游戏', BTTEXTCOLOR, BTCOLOR, WINWIDTH - 85, WINHEIGHT - 40)
winSet.blit(new_surf, new_rect)
if msg:
        msgSurf, msgRect = makeText(msg, MSGCOLOR, None, 5, 5)
        pygame.image.save(msgSurf, 'msg.png')  # 将msgSurf存为名为msg.png的图片
        imgSurf = pygame.image.load('msg.png')  # 加载图片
        WINSET.blit(imgSurf, msgRect)
  1. 可直接绘制msgSurf,不必存为图片加载图片。
  • drawBoard函数,用于绘制动态界面,负责了绘制消息、绘制序列列表方块和游戏整个方块的外边框。
    利用一个双层循环,循环序列列表,调用drawTile函数,,绘制方块及数字。而drawTile 函数调用了getLeftTopOfTile函数,
    输入参数行列,根据行列,计算方块左上角 距离窗口原点 纵横坐标距离,并返回距离y轴、x轴的距离,用于确定绘制的方块位置。
    getLeftTopOfTile先把整个拼盘当作一个整体,计算出相对于窗口的中心位置,但是并不绘制一整个方块,而是根据行列,进行一定的偏移,绘制出全部方块及渲染数字到方块上。
    最后传入行列(0,0),即最左上角的方块的行列,确定其距离x,y轴的距离,绘制整个拼盘的外边框。
    至此,消息、方块、按钮等都以绘制完成,视图层呈现出来了。
4、Controller

controller负责控制整个游戏的逻辑运行,包括推盘序列初始化、接收用户输入、对用户输入进行处理、以及退出游戏。

  1. 视图呈现之后,但是推盘序列最初始还是顺序排列的,我们需要将它打乱才可以进行游戏,通过移动将推盘完成顺序排列。
  • generateNewPuzzle通过形参numSlides,获取随机移动的次数,目的是打乱推盘序列。numSlides的实参就是AUTOMOVE全局变量,通过rondom模块,随机获取的一个50-100之间的整数。
  • 首先通过调用getStartingBoard函数,获取初始的推盘序列,drawBoard传入序列 绘制界面。
  • 定义初始移动方向为None,getRandomMove传入序列以及方向,获取随机移动方向,移动方向有4个,但是当空格在推盘第一行时,它是不可以向上移动的,所以应从4个移动方向中,移除无效的移动方向。其他类似判断。random.choice将从列表中随机获取一个移动方向。isValidMove用于判断无效的移动方向。
  • getInput获取用户输入,先定义变量userInput初始值为None,根据获取的点击位置,通过getSpotClicked函数,返回点击的方块所在行列,如与方块未产生碰撞,则返回(None,None),表示点击的空白区域。
  • 如果序列与初始序列相同,表示已完成,不予点击,直接跳出。
  • 但是点击方块,也并不能让所有方块生效移动,只有当点击方块的位置在空格旁边的时候,判断被点击方块与空格的位置关系,如果点击方块在空格右边,设置移动方向向左,其他类似。函数返回用户输入userInput。
  • processing函数接收getInput的返回值,序列,以及应设置的消息,对用户的输入进行处理,判断推盘状态,是待完成还是已完成,设置对应的提示msg。再对用户输入判断,点击的新按钮还是移动方向。做出对应的相应。
  • checkForQuit判断用户是否退出。

随机生成乱序二维列表

import random
COL = 4
ROW = COL
x = list(range(1, COL * ROW))
x.append(None)
print(x)
random.shuffle(x)
print(x)
init = []
for i in range(COL):
    clunm = []
    for j in range(ROW):
        clunm.append(x[COL*i+j])
    init.append(clunm)
print(init)

二维元祖与列表相互转换

# 列表转换元祖
mianBoard = [[6, 7, 1], [None, 3, 2], [8, 4, 5]]
RESETBoard = tuple(tuple(tuple(items)) for items in tuple(mianBoard))
print(RESETBoard)
>>>((6, 7, 1), (None, 3, 2), (8, 4, 5))
# 元祖转换列表
RESETBoard = ((6, 7, 1), (None, 3, 2), (8, 4, 5))
mianBoard = list(list(list(items)) for items in list(RESETBoard))
print(mianBoard)
>>>[[6, 7, 1], [None, 3, 2], [8, 4, 5]]

算法相关


深度优先搜索DFS


深度优先搜索算法(英语:Depth-First-Search,DFS)是一种用于遍历或搜索算法。这个算法会尽可能深的搜索树的分支。当节点v的所在边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。[1](p. 603)这种算法不会根据图的结构等信息调整执行策略[来源请求]

深度优先搜索是图论中的经典算法,利用深度优先搜索算法可以产生目标图的拓扑排序表[1](p. 612),利用拓扑排序表可以方便的解决很多相关的图论问题,如无权最长路径问题等等。


广度优先搜索BFS


宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。

广度优先搜索算法(英语:Breadth-First Search,缩写为BFS),又译作宽度优先搜索,或横向优先搜索,是一种图形搜索算法。简单的说,BFS是从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止。广度优先搜索的实现一般采用open-closed表.

BFS是一种暴力搜索算法,目的是系统地展开并检查中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能地址,彻底地搜索整张图,直到找到结果为止。BFS并不使用经验法则算法


贪心算法


贪心算法(英语:greedy algorithm),又称贪婪算法,是一种在每一步选择中都采取在当前状态下最好或最优(即最有利)的选择,从而希望导致结果是最好或最优的算法。[1]比如在旅行推销员问题中,如果旅行员每次都选择最近的城市,那这就是一种贪心算法。

贪心算法在有最优子结构的问题中尤为有效。最优子结构的意思是局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解。

贪心算法与动态规划的不同在于它对每个子问题的解决方案都做出选择,不能回退。动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能。

贪心法可以解决一些最优化问题,如:求中的最小生成树、求哈夫曼编码……对于其他问题,贪心法一般不能得到我们所要求的答案。一旦一个问题可以通过贪心法来解决,那么贪心法一般是解决这个问题的最好办法。由于贪心法的高效性以及其所求得的答案比较接近最优结果,贪心法也可以用作辅助算法或者直接解决一些要求结果不特别精确的问题。在不同情况,选择最优的解,可能会导致辛普森悖论(Simpson’s Paradox),不一定出现最优的解。

贪心算法在数据科学领域被广泛应用,特别是金融工程。其中一个贪心算法例子就是Ensemble method。

  1. 创建数学模型来描述问题。
  2. 把求解的问题分成若干个子问题
  3. 对每一子问题求解,得到子问题的局部最优解。
  4. 把子问题的解局部最优解合成原来解问题的一个解。

实现该算法的过程:

从问题的某一初始解出发;while 能朝给定总目标前进一步 do,求出可行解的一个解元素;

最后,由所有解元素组合成问题的一个可行解。


文件的使用


–用户登录


先创建一个目录falg

import os
def c_flag():
    with open("flag", "w") as file:
        file.write("1")
def init():
    with open("u_root", "w") as file:
        root = {"username": "root", "password": "123456"}
        file.write(str(root))
    os.mkdir("users")
def user_login():
    while 1:
        print("********用户登录*********")
        user_name = input("请输入账户名:")
        user_psw = input("请输入密码:")
        user_list = os.listdir("./users")
        flag = 0
        for user in user_list:
            if user == user_name:
                flag = 1
                print("登录中。。。。。")
                file = "./users/" + user_name
                file_user = open(file)
                user_info = eval(file_user.read())
                if user_psw == user_info["u_psw"]:
                    print("登录成功")
                    print("-----------------")
                    break
                else:
                    print("密码错误")
        if flag == 1:
            break
        elif flag == 0:
            print("没有此用户,请先注册")
            break
        else:
            print("参数有误")
def user_register():
    user_username = input("请输入账户名:")
    user_psw = input("请输入密码:")
    user_name = input("请输入昵称:")
    user = {"u_username": user_username, "u_psw": user_psw, "u_name": user_name}
    user_path = "./users/" + user_username
    with open(user_path, "w") as file_user:
        file_user.write(str(user))
def root_login():
    while 1:
        print("*******管理员登录*******")
        root_name = input("请输入账户名:")
        root_psw = input("请输入密码:")
        file_root = open("u_root")
        root = eval(file_root.read())
        if root_name == root["username"] and root_psw == root["password"]:
            print("登录成功")
            break
        else:
            print("账号或密码有误")
def user_select():
    while 1:
        user_type_select = input("请选择用户类型:")
        if user_type_select == "1":
            root_login()
            break
        elif user_type_select == "2":
            while 1:
                select = input("是否需要注册?(y/n)")
                if select == "y":
                    print("------用户注册------")
                    user_register()
                    break
                elif select == "n":
                    print("------用户登录------")
                    break
                else:
                    print("输入有误,请重新输入!(y/n)")
            user_login()
            break
        else:
            print("输入有误,请重新输入!(1/2)")
def print_login_menu():
    print("-----用户选择-----")
    print("1-管理员登录")
    print("2-用户登录")
    print("------------------")
def main():
    flag = open("flag")
    word = flag.read()
    if word == "0":
        print("首次启动")
        flag.close()
        c_flag()
        init()
        print_login_menu()
        user_select()
    elif word == "1":
        print("欢迎回来")
        print_login_menu()
        user_select()
    else:
        print("初始化参数错误")
if __name__ == '__main__':
    main()

对文件中的数字排序


应有一个名为 number 的文件,里面存入以空格分隔的数字,例:

21 34 4 5 45 5 45 45 2 3 76 542 542

with open("number", "r") as file:
    for fil in file:
        numberList = []
        dlist = []
        # 分割存入列表
        for f in list(fil):
            if f == "\40":  # 以空格分割
                num = "".join(dlist)
                dlist.clear()
                numberList.append(int(num))
            else:
                dlist.append(f)
        numberList.sort()
        print(numberList)

或 直接 使用split函数 分割

但是分割后的数字为字符串类型,需转型

with open("number", "r") as file:
    for fil in file:
        numberList = fil.split(" ")
        l = []
        for i in numberList:
            l.append(int(i))
        l.sort()
        print(l)

或 直接使用

numberList = [int(x) for x in numberList]

转型

with open("number", "r") as file:
    for fil in file:
        numberList = fil.split(" ")
        numberList = [int(x) for x in numberList]
        numberList.sort()
        print(numberList)

注释实现


实现类似python注释的功能,读取"u_root1"文件,但是不读取"#"后的内容

strs = []
with open("u_root1", "r") as file:
    for s in file:
        for jing in list(s):
            if jing == "#":
                break
            strs.append(jing)
            # print(jing, end="")
        strs.append("\n")
zz = "".join(strs)
print(zz)

格式

print("我的名字是:%s,年龄为:%d" % ('小强', 13))
print("我的名字是:{},年龄为:{}".format('小强', 13))
print("我的名字是:{1},年龄为:{0}".format(13, '小强'))
# print("我的名字是:%s,年龄为:%d" % (13, '小强'))  报错
a = "q_"
# 如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。
print(a.isalpha()) 

绘制直方图

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print(np.random.rand(10, 4))  # 4行10列 的二维列表
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(stacked=True, kind="bar")
plt.show()

曲线图

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Simhei']  # 中文
plt.rcParams['axes.unicode_minus'] = False  # 符号
data = np.arange(0, 1.1, 0.01)
plt.title("曲线")
plt.xlabel("x")
plt.ylabel("y")
plt.xticks([0, 0.5, 1])
plt.yticks([0, 0.5, 1.0])
plt.plot(data, data ** 2)
plt.plot(data, data ** 3)
plt.legend(["y=x^2", "y=x^3"])
plt.show()
mport numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Simhei']  # 中文
plt.rcParams['axes.unicode_minus'] = False  # 符号
# plt.figure(figsize=(10, 6), facecolor='gray')
# # plt.axes([0.1, 0.5, 0.7, 0.3])
# # plt.subplot(323)
# plt.subplots(2, 2)
# plt.show()  # 绘图区域
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, s, 'm:')
plt.plot(x, c, 'c--')
plt.show()

雷达图

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Simhei']  # 中文
plt.rcParams['axes.unicode_minus'] = False  # 符号
courses = np.array(['Java', 'Python', 'C,', 'SpringBoot', 'Vue', 'JavaScript'])
scores = np.array([[95, 75, 74],
                   [95, 23, 86],
                   [65, 75, 86],
                   [95, 75, 98],
                   [56, 75, 86],
                   [95, 87, 49]])
data_length = len(scores)  # 6
angles = np.linspace(0, 2 * np.pi, data_length, endpoint=False)
scores = np.concatenate((scores, [scores[0]]))  # 7
angles1 = np.concatenate((angles, [angles[0]]))  # 7
plt.polar(angles1, scores, 'o-', linewidth=3)
plt.thetagrids(angles * 180 / np.pi, courses, fontproperties='simhei')
plt.title("成绩评估")
plt.legend(['软件1909', '软件1909', '软件1909'], loc=(0.94, 0.80), labelspacing=0.1)
plt.show()

pandas模块

import pandas as pd
import numpy as np
df_obj = pd.DataFrame([[11.0, np.nan, 5.0, 6.0], [1.0, np.nan, np.nan, 8.0]])
print(df_obj)
df_obj.isnull()
#        0     1      2      3
# 0  False  True  False  False
# 1  False  True   True  False
df_obj.dropna(axis=1)
#       0    3
# 0  11.0  6.0
# 1   1.0  8.0
相关文章
|
4月前
|
Python
小笔记:Python 使用字符串调用函数
小笔记:Python 使用字符串调用函数
42 0
|
4月前
|
JavaScript 前端开发 测试技术
[小笔记]TypeScript/JavaScript模拟Python中的Range函数
[小笔记]TypeScript/JavaScript模拟Python中的Range函数
28 0
|
11天前
|
存储 索引 Python
|
4月前
|
JavaScript 前端开发 测试技术
[小笔记]TypeScript/JavaScript模拟Python中的zip(不使用map)
[小笔记]TypeScript/JavaScript模拟Python中的zip(不使用map)
19 0
|
4月前
|
C# Python
C# 笔记3 - 重载一系列像python那样的print()方法
C# 笔记3 - 重载一系列像python那样的print()方法
30 1
|
4月前
|
关系型数据库 MySQL 数据库
MySQL命令笔记+Python案例
MySQL命令笔记+Python案例
47 0
|
4月前
|
存储 Python
Python:核心知识点整理大全16-笔记-2
Python:核心知识点整理大全16-笔记
19 0
|
4月前
|
存储 Python
Python:核心知识点整理大全16-笔记-1
Python:核心知识点整理大全16-笔记
27 0
|
4月前
|
Python
python笔记
python笔记
|
4月前
|
前端开发 API 开发工具
Python实现post请求小红书笔记详情数据接口
Python实现post请求小红书笔记详情数据接口
80 1