Python学习笔记(6)List and Keyboard Control

来源:互联网 发布:打电话变女声软件 编辑:程序博客网 时间:2024/04/30 22:04

下面的笔记内容来自coursera上的Python公开课。

List注意1 List中的value类型可以不一致
list_test=['abc',1.3,4,[4,5,6]] print list_test         #['abc', 1.3, 4, [4, 5, 6]]

List注意2 list分为两半list
If we want to split a list my_list into two halves, which of the following uses slices to do so correctly? More precisely, if the length of my_list is 2n, i.e., even, then the two parts should each have length n. If its length is 2n+1, i.e., odd, then the two parts should have lengths n and n+1. my_list[: len(my_list) // 2] and my_list[len(my_list) // 2 :] my_list[0 : len(my_list) // 2] and my_list[len(my_list) // 2 : len(my_list)]

List注意3 看下面几个列子,理解list是否是global variable

#################################### Mutation vs. assignment################# Look alike, but differenta = [4, 5, 6]b = [4, 5, 6]print "Original a and b:", a, bprint "Are they same thing?", a is ba[1] = 20print "New a and b:", a, bprint################# Aliasedc = [4, 5, 6]d = cprint "Original c and d:", c, dprint "Are they same thing?", c is dc[1] = 20print "New c and d:", c, dprint################# Copiede = [4, 5, 6]f = list(e)print "Original e and f:", e, fprint "Are they same thing?", e is fe[1] = 20print "New e and f:", e, fprint#################################### Interaction with globalsa = [4, 5, 6]def mutate_part(x):    a[1] = xdef assign_whole(x):    a = xdef assign_whole_global(x):    global a    a = xmutate_part(100)print aassign_whole(200)print aassign_whole_global(300)print a

结果如下

Original a and b: [4, 5, 6] [4, 5, 6]Are they same thing? FalseNew a and b: [4, 20, 6] [4, 5, 6]Original c and d: [4, 5, 6] [4, 5, 6]Are they same thing? TrueNew c and d: [4, 20, 6] [4, 20, 6]Original e and f: [4, 5, 6] [4, 5, 6]Are they same thing? FalseNew e and f: [4, 20, 6] [4, 5, 6][4, 100, 6][4, 100, 6]300

Tuple 1 Tuple不支持mutation 
Tuple不支持mutation, 即tuple的值在初始化之后不能更改, tuple存在的意义是,保护数据。

#################################### Lists (mutable) vs. tuples (immutable)print [4, 5, 6]print (4, 5, 6)print type([4, 5, 6])print type((4, 5, 6))a = [4, 5, 6]a[1] = 100print ab = (4, 5, 6)b[1] = 100  #Line 17: TypeError: 'tuple' does not support item assignmentprint b

str str不支持item assignment
以下code是错误的
string = "Larch"
string[1] = "u"
print string   #Line 2: TypeError: 'str' does not support item assignment

KeyboardControl例1 Keyboard echo

import simplegui# initialize statecurrent_key = ' '# event handlersdef keydown(key):    global current_key    current_key = chr(key)   def keyup(key):    global current_key    current_key = ' '   def draw(c):    # NOTE draw_text now throws an error on some non-printable characters    # Since keydown event key codes do not all map directly to    # the printable character via ord(), this example now restricts    # keys to alphanumerics       if current_key in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":        c.draw_text(current_key, [10, 25], 20, "Red")          # create frame            f = simplegui.create_frame("Echo", 35, 35)# register event handlersf.set_keydown_handler(keydown)f.set_keyup_handler(keyup)f.set_draw_handler(draw)# start framef.start()


KeyboardControl例2 Left箭头,Right箭头,Up箭头,Down箭头控制光标的移动

# control the position of a ball using the arrow keysimport simplegui# Initialize globalsWIDTH = 600HEIGHT = 400BALL_RADIUS = 20ball_pos = [WIDTH / 2, HEIGHT / 2]# define event handlersdef draw(canvas):    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")def keydown(key):    vel = 4    if key == simplegui.KEY_MAP["left"]:        ball_pos[0] -= vel    elif key == simplegui.KEY_MAP["right"]:        ball_pos[0] += vel    elif key == simplegui.KEY_MAP["down"]:        ball_pos[1] += vel    elif key == simplegui.KEY_MAP["up"]:        ball_pos[1] -= vel            # create frame frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT)# register event handlersframe.set_draw_handler(draw)frame.set_keydown_handler(keydown)# start frameframe.start()


KeyboardControl例3  光标自动移动 (借助timer来实现)
# Ball motion with an explicit timerimport simplegui# Initialize globalsWIDTH = 600HEIGHT = 400BALL_RADIUS = 20init_pos = [WIDTH / 2, HEIGHT / 2]vel = [0, 3]  # pixels per ticktime = 0# define event handlersdef tick():    global time    time = time + 1def draw(canvas):    # create a list to hold ball position    ball_pos = [0, 0]    # calculate ball position    ball_pos[0] = init_pos[0] + time * vel[0]    ball_pos[1] = init_pos[1] + time * vel[1]        # draw ball    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")# create frameframe = simplegui.create_frame("Motion", WIDTH, HEIGHT)# register event handlersframe.set_draw_handler(draw)timer = simplegui.create_timer(100, tick)# start frameframe.start()timer.start()

KeyboardControl例4 光标自动移动 (不借助timer来实现,因为draw()函数默认会以一定频率重复执行)

1 If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.
2 问题 draw()里的ball_pos明明不是global variable,为什么update表现和global variable的update表现是一样的呢?因为在函数中对变量如果进行mutation,则把此变量看做global variable;如果进行assign且声明此变量为global,则把此变量看做global variable;如果进行assign并且不声明此变量为global,把此变量看做local variable.

# Ball motion with an implicit timerimport simplegui# Initialize globalsWIDTH = 600HEIGHT = 400BALL_RADIUS = 20ball_pos = [WIDTH / 2, HEIGHT / 2]vel = [0, 1] # pixels per update (1/60 seconds)# define event handlersdef draw(canvas):    # Update ball position    ball_pos[0] += vel[0]    ball_pos[1] += vel[1]    # Draw ball    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")# create frameframe = simplegui.create_frame("Motion", WIDTH, HEIGHT)# register event handlersframe.set_draw_handler(draw)# start frameframe.start()

例5 小球碰撞的Python模拟
撞到左墙,类似向量的加减法
v[0] = -v[0]
v[1] =  v[1]


import simplegui# Initialize globalsWIDTH = 600HEIGHT = 400BALL_RADIUS = 20ball_pos = [WIDTH / 2, HEIGHT / 2]vel = [-40.0 / 60.0,  5.0 / 60.0]# define event handlersdef draw(canvas):    # Update ball position    ball_pos[0] += vel[0]    ball_pos[1] += vel[1]        # collide and reflect off of left hand side of canvas    if ball_pos[0] <= BALL_RADIUS:        vel[0] = - vel[0]        # Draw ball    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")# create frameframe = simplegui.create_frame("Ball physics", WIDTH, HEIGHT)# register event handlersframe.set_draw_handler(draw)# start frameframe.start()

例子6 从position和velocity入手改变小球移动

# control the velocity of a ball using the arrow keysimport simplegui# Initialize globalsWIDTH = 600HEIGHT = 400BALL_RADIUS = 20ball_pos = [WIDTH / 2, HEIGHT / 2]vel = [0, 0]# define event handlersdef draw(canvas):    # Update ball position    ball_pos[0] += vel[0]    ball_pos[1] += vel[1]    # Draw ball    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")def keydown(key):    acc = 1    if key==simplegui.KEY_MAP["left"]:        vel[0] -= acc    elif key==simplegui.KEY_MAP["right"]:        vel[0] += acc    elif key==simplegui.KEY_MAP["down"]:        vel[1] += acc    elif key==simplegui.KEY_MAP["up"]:        vel[1] -= acc            print ball_pos    # create frame frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT)# register event handlersframe.set_draw_handler(draw)frame.set_keydown_handler(keydown)# start frameframe.start()


0 0
原创粉丝点击