分类: Python

  • python集合元素的删除

    在Python中,集合(set)是一个无序的数据结构,它不保持元素的插入顺序。因此,当你print一个集合时,元素的输出顺序可能看起来是随机的,实际上这个顺序是由集合内部的哈希表决定的。

    attendees = {'Alice Smith', 'Bob Jones', 'Carol', 'David'}
    print(attendees)
    

    它输出的结果可能有点出人意料。

    展开/折叠结果 >>> print(attendees)
    {'Carol', 'Alice Smith', 'Bob Jones', 'David'}

    这体现了集合的无序性,如果我们想从中删除元素,比较适合和安全的方法是写一个函数。

    def remove_attendees_with_first_name(attendees, name):   # 定义一个函数
        to_remove = set()   # 新建一个空集合
        for att in attendees:   # for循环,循环attendees的每一个元素
            if att.startswith(name):   # 检查每一个元素,是否是以给定的name变量开头
                to_remove.add(att)   # 如果是,把该元素放入新建的集合
        for remove in to_remove:   # 第二个for循环,遍历新建的集合
            attendees.discard(remove)   # 从attendees集合中移除to_remove集合中的每一个元素
    remove_attendees_with_first_name(attendees, 'Bob')   # 我们移除Bob开头的元素
    print(attendees)  # 输出将不包含 'Bob Jones'
    
    展开/折叠结果 >>> remove_attendees_with_first_name(attendees, 'Bob')
    >>> print(attendees) # 输出将不包含 'Bob Jones'
    {'Carol', 'Alice Smith', 'David'}
  • python的集合

    集合,也是一个把一大堆内容放在一起的功能。

    a_set = {"张三", "李四", "王五", "这六"}
    print(a_set)
    
    a_set.add('那七')
    print(a_set)
    
    a_set.remove('李四')
    print(a_set)
    
    if '张三' in a_set:
        print('张三在集合中。')
    else:
        print('张三不再在集合中。')
    
    展开/折叠结果 {'王五', '张三', '李四', '这六'}
    {'张三', '这六', '李四', '王五', '那七'}
    {'张三', '这六', '王五', '那七'}
    张三在集合中。
  • python的列表的嵌套

    列表里面可以包含列表。

    my_list = [ [1, 2], [3, 4] ]
    print(my_list[0][1]+my_list[1][0])
    

    可以自己猜一猜,结果是什么。

    5

    其实上面的列表还可以写成另一种写法,结果是完全一样的。这样写可能更好理解一些。

    my_list = [ [1, 2], 
                [3, 4] ]
    print(my_list[0][1]+my_list[1][0])
    

    我们来实例一个计算每个人平均分的代码。

    my_list = [ ['张三', 98, 89], 
                ['李四', 78, 90] ] 
    
    def print_overall_grade_average(my_list): 
        for i in range(len(my_list)): 
            grade_sum = 0 
            for j in range(1, len(my_list[i])): 
                grade_sum += my_list[i][j] 
            print(my_list[i][0], str(grade_sum/(len(my_list[0])-1)))
    
    print_overall_grade_average(my_list)
    

    这里,有两个人,可以增加很多人,下面的函数用来计算每个人的平均数。

    >>> print_overall_grade_average(my_list)
    张三 93.5
    李四 84.0
  • python列表的索引

    和字符串一样,python给列表内置了索引功能,从0开始,1,2,3,…往后排。

    numbers = [2, 5, 15, 20, 25, 30, 25]
    numbers[2] = 100
    numbers[4] += 10
    numbers[-1] -= 5
    numbers[0] = numbers[1]
    print(numbers)
    

    根据以前学的知识,应该能猜到,这个代码的结果是什么。

    [5, 5, 100, 20, 25, 30, 20]

    要把上面列表中的数字一个一个的输出出来,需要用for循环。

    for i in range(len(numbers)):
        print(numbers[i])
    

    这里的range()用于生成一个从0开始,到number长度的数列。

    5
    5
    100
    20
    25
    30
    20
  • python的列表

    python可以用列表来记录一些列数据。这样,一个变量中就可以放更多的内容。

    names = ['张三', '李四', '王五', '这六']
    print(names)
    names.append('那七')   # 追加一个
    print(names)
    if '张三' in names:
        names.remove('张三')   # 移除一个
    else:
        print('张三不存在。')
    print(names)
    
    >>> names = ['张三', '李四', '王五', '这六']
    >>> print(names)
    ['张三', '李四', '王五', '这六']
    >>> names.append('那七') # 追加一个
    >>> print(names)
    ['张三', '李四', '王五', '这六', '那七']
    >>> if '张三' in names:
    ... names.remove('张三') # 移除一个
    ... else:
    ... print('张三不存在。')
    ...
    >>> print(names)
    ['李四', '王五', '这六', '那七']
  • python写一个to-do列表

    这个是一个练习,去尝试写一个to do list,用之前已经学过的知识:

    # 连接文件
    FILE_NAME = 'todo.txt'
    
    # 展示todo列表
    def show_todo_list():
    
        todo_file = open(FILE_NAME, 'r')
        counter = 1
        for line in todo_file:
            line = line.strip('\n')
            print('  * (' + str(counter) + ') ' + line)
            counter += 1
        if counter == 1:
            print("没有列表!")
        todo_file.close()
    
    # 增加内容
    def add_to_todo_list(item):
        # 追加模式打开文件
        todo_file = open(FILE_NAME, 'a')
        todo_file.write(item + '\n')
        todo_file.close()
    
    # 删除内容
    def remove_from_todo_list(number):
        # 只读打开文件
        todo_file = open(FILE_NAME, 'r')
        new_content = ''
        counter = 1
        for line in todo_file:
            if counter != number:
                new_content += line
            counter += 1
        todo_file.close()
        # 写入模式打开文件
        todo_file = open(FILE_NAME, 'w')
        todo_file.write(new_content)
        todo_file.close()
    
    def main():
        command = ''   # 初始化命令
        while command != 'exit':
            command = input('show, add, remove, or exit? ')
            if command == 'show':
                show_todo_list()
            elif command == 'add':
                task = input('What task needs to be added? ')
                add_to_todo_list(task)
            elif command == 'remove':
                number = int(input('What item number should be removed? '))
                remove_from_todo_list(number)
        print('结束!')
    
    main()
    

    在相同的目录下,还需要一个todo.txt,请自行添加内容,很遗憾,该代码不支持中文。

  • python画一朵花

    python不仅可以生成文字,也能生成图片,当然要复杂一些。首先,我们要把一个集成了画图功能的代码保存成【graphics.py】,然后调用这个程序。

    import tkinter
    import time
    
    class graphics:
        def __init__(self, w, h, title):
            ''' Initialize the graphics object.
            Creates a new tkinter Tk object, 
            and a tkinter Canvas object,
            placed insize the Tk object.
            '''
            self.primary = tkinter.Tk()
            self.primary.title(title)
            self.primary.geometry('%dx%d+%d+%d' % (w, h, 50, 100))
            self.canvas = tkinter.Canvas(self.primary, width=w, height=h, highlightthickness=0)
            self.canvas.focus_set()
            self.canvas.pack()
            self.mouse_x = 0
            self.mouse_y = 0
            self.images = {}
            self.frame_count = 0
            self.__handle_motion()
    
        '''
        BEGIN PRIVATE FUNCTION(S)
        '''
    
        def __handle_motion(self):
            ''' Ensure mouse x and y coordinates are updated when mouse moves.
            '''
            def motion_action(event):
                self.mouse_x = event.x
                self.mouse_y = event.y
            self.canvas.bind('<Motion>', motion_action)
    
        '''
        END PRIVATE FUNCTION(S)
        '''
    
        def resize(self, width, height):
            self.primary.geometry(str(width) + 'x' + str(height))
    
        def text(self, x, y, content, fill='black', size=17):
            ''' Draw text on the canvas.
            Must always specify the text, x, y position.
            Can optionally specify the fill color and size.
            '''
            text = self.canvas.create_text(x, y, text=content, fill=fill, font=('Arial', size), anchor='nw')
            self.canvas.move(text, 0, 0)
       
        def set_left_click_action(self, callee):
            ''' Call the callee function whenever the left click happens.
            callee should take two parameters, the mouse x and mouse y coordinates.
            '''
            def left_click_action(event):
                callee(self, event.x, event.y)
            ''' <Button-1> is the left-most mouse button '''
            self.canvas.bind('<Button-1>', left_click_action)
        
        def set_right_click_action(self, callee):
            ''' Call the callee function whenever the right click happens.
            callee should take two parameters, the mouse x and mouse y coordinates.
            '''
            def right_click_action(event):
                callee(self, event.x, event.y)
            ''' <Button-2> or <Button-3> is the right-most mouse button.
            Both are set just in case '''
            self.canvas.bind('<Button-2>', right_click_action)
            self.canvas.bind('<Button-3>', right_click_action)
        
        def set_keyboard_action(self, callee):
            ''' Call the callee function whenever a keyboard key is pressed.
            callee should take one parameter, a char representing the key.
            '''
            def keyboard_action(event):
                callee(self, event.char)
            self.canvas.bind('<KeyPress>', keyboard_action)
    
        def get_color_string(self, red, green, blue):
            ''' accepts three ints that should represent and RGB color.
            Returns a hex string'''
            hex_string = hex(red)[2:].rjust(2, '0') + \
                         hex(green)[2:].rjust(2, '0') + \
                         hex(blue)[2:].rjust(2, '0')
            return '#' + hex_string
    
        def triangle(self, x1, y1, x2, y2, x3, y3, fill='black'):
            ''' Draw a triangle.
            The three corners of the triangle are specified with the parameter coordinates.
            '''
            r = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, fill=fill)
            self.canvas.move(r, 0, 0)
        
        def line(self, x1, y1, x2, y2, fill='black', width=3):
            ''' Draw a line.
            The two ends of the line are specified with the parameter coordinates.
            '''
            r = self.canvas.create_line(x1, y1, x2, y2, fill=fill, width=width)
            self.canvas.move(r, 0, 0)
        
        def ellipse(self, x, y, w, h, fill='black'):
            ''' Draw an ellipse on the canvas.
            Specify x, y (center of ellipse) and width / height.
            '''
            r = self.canvas.create_oval(x-(w/2), y-(h/2), x+(w/2), y+(h/2), fill=fill, outline='')
            self.canvas.move(r, 0, 0)
        
        def rectangle(self, x, y, w, h, fill='black'):
            ''' Draw a rectangle on the canvas.
            Specify x, y (top-left corner) and width / height.
            '''
            r = self.canvas.create_rectangle(x, y, x+w, h+y, fill=fill, outline='')
            self.canvas.move(r, 0, 0)
        
        def image(self, x, y, up_scale, down_scale, file_name):
            ''' Draw an image on the canvas.
            Specify x, y (top-left corner) and width / height.
            '''
            if file_name not in self.images:
                self.images[file_name] = tkinter.PhotoImage(file=file_name)
            self.images[file_name] = self.images[file_name].zoom(up_scale, up_scale)
            self.images[file_name] = self.images[file_name].subsample(down_scale, down_scale)
            i = self.canvas.create_image(x, y, anchor='nw', image=self.images[file_name])
            self.canvas.move(i, 0, 0)
            return self.images[file_name]
    
        def update(self):
            ''' Does an idle task update and regular update.
            '''
            self.primary.update_idletasks()
            self.primary.update()
    
        def frame_space(self, frame_rate):
            ''' Sleeps for a time that corresponds to the provided frame rate.
            '''
            sleep_ms = 1.0 / float(frame_rate)
            time.sleep(sleep_ms)
    
        def update_frame(self, frame_rate):
            ''' Updates and sleeps.
            This should be called at the end of each iteration of a users draw loop.
            '''
            self.update()
            self.frame_space(frame_rate)
            self.frame_count += 1
        
        def draw(self):
            ''' Draw a static graphic. Should be called after specifying the shapes to draw.
            '''
            self.primary.mainloop()
        
        def clear(self):
            ''' Clears the canvas.
            '''
            self.canvas.delete('all')
    

    将上面的代码保存成【graphics.py】,并在相同的目录下,新建一个【flower.py】,编辑这个文件:

    from graphics import graphics   # 导入graphics文件
    def main():   # 定义主函数
        print("绘制一朵花")   # 输出文本
        myCanvas = graphics(500, 500, "Flower")   # 新建一个画布,宽500,高500,名字为花
        myCanvas.rectangle(0, 400, 500, 100, "green")   # 矩形,在0,400位置画宽500,高100,绿色
        myCanvas.rectangle(0, 0, 500, 400, "light blue")   # 在0,0位置画宽500,高400的淡蓝色矩形
        myCanvas.line(250, 200, 250, 450, "dark green", 5)   # 在250,200处画到250,450的线,深绿色,宽度5
        myCanvas.triangle(250, 150, 250, 250, 400, 200, "purple")   # 画三角形,给3个顶点坐标,紫色
        myCanvas.triangle(250, 150, 250, 250, 100, 200, "purple")   # 画三角形,给3个顶点坐标,紫色
        myCanvas.triangle(300, 200, 200, 200, 250, 50, "purple")   # 画三角形,给3个顶点坐标,紫色
        myCanvas.triangle(300, 200, 200, 200, 250, 350, "purple")   # 画三角形,给3个顶点坐标,紫色
        myCanvas.ellipse(250, 200, 75, 75, "orange")   # 在250,200处画宽75高75的椭圆,橙色
        myCanvas.draw()   # 绘制
    main()
    

    结果为:

  • python计算1加到100

    有这样一个题目,计算1+2+3一直加到100,它的总和是多少。我们用新学过的递归来尝试解决这个问题。

    def leijia(n):   # 定义一个函数,叫做leijia,包括一个参数n
        if n < 1:   # 如果n小于1,也就是n=0的情况,计算的是0不加减
            return 0   # 因此,此时返回0
        return n + leijia(n-1)   # 正常返回值为n+(n-1)的累加,用迭代leijia(n-1)表示上一次的结果
    
    print( leijia(100) )   # 调用累加函数
    

    有了这个程序,从1加到任何数字的和都能非常轻易的计算出来。上面的结果为:

    >>> print( leijia(100) )
    5050
  • python的递归

    递归是一个函数自己调用自己。听起来很神奇,就像我们自己举起自己是根本做不到的一样,但是程序还真就可以。假设我们要说5次hello:

    for index in range(0, 5):
        print('Hello')
    

    用已经学过的for循环,很简单就实现了。现在我们用函数调用自身来实现同样的功能。

    def say_hi(n):
        if n < 1:
            return
        print('Hello')
        say_hi(n-1)
    say_hi(5)
    

    发现了吗?同样的功能,递归函数通过自身的调用,避免了使用循环。

    >>> say_hi(5)
    Hello
    Hello
    Hello
    Hello
    Hello
  • python字符串切片

    切片,听起来像在做菜。实际上当然不是。切片是把字符串分成不同的段落。比如:“你好我好都好”这样一句话,我想要没两个字分一段,就可以这样。

    text = '你好我好都好'
    width = 2
    while len(text) > 0:
        line = text[:width]
        print(line)
        text= text[width:]
    

    结果为:

    你好
    我好
    都好