下面的笔记内容来自coursera上的Python公开课。
list相关操作例2
list相关操作例3
list相关操作例4
注意LIST在循环中不能进行元素删除!!!
注意这个example中在def click(pos)中
在循环中进行了删除和增加。注意删除和增加是分别在两个list中完成的,如果在循环中对同一个list中一边删除一边加入,可能会有问题,如陷入无限循环。
iteration 各种操作演示
list comprehension
2 Dictionary
2.1 dictionary的定义
注意dictionary的key可以是各种各样的
2.2 dictionary
例3 字典版的编码解码器
3 Mouse Input例1 小球随鼠标运动而运动
Mouse input的输入参数是什么?
4 image drawing
1 list的常见用法
list = [1,3,5,7,9]
in
if 3 in list:
print “in list”
else:
print “not in"
index
print list.index(“5”)
append
list.append(11) #list = [1,3,5,7,9,11]
extend
pop
list.pop() #list = [1,3,5,7,9]
list.pop(2) #list = [1,3,7,9]
list相关操作例1
# Simple task list
import simplegui
tasks = []
# Handler for button
def clear():
global tasks
tasks = []
# Handler for new task
def new(task):
tasks.append(task)
# Handler for remove number
def remove_num(tasknum):
n = int(tasknum)
if n > 0 and n <= len(tasks):
tasks.pop(n-1)
# Handler for remove name
def remove_name(taskname):
if taskname in tasks:
tasks.remove(taskname)
# Handler to draw on canvas
def draw(canvas):
n = 1
for task in tasks:
pos = 30 * n
canvas.draw_text(str(n) + ": " + task, [5, pos], 24, "White")
n += 1
# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Task List", 600, 400)
frame.add_input("New task:", new, 200)
frame.add_input("Remove task number:", remove_num, 200)
frame.add_input("Remove task:", remove_name, 200)
frame.add_button("Clear All", clear)
frame.set_draw_handler(draw)
# Start the frame animation
frame.start()
list相关操作例2
# Examples of mouse input
import simplegui
import math
# intialize globals
width = 450
height = 300
ball_list = []
ball_radius = 15
ball_color = "Red"
# helper function
def distance(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define event handler for mouse click, draw
def click(pos):
ball_list.append(pos)
# if distance(ball_pos, pos) < ball_radius:
# if ball_color == "Red":
# ball_color = "Green"
# else:
# ball_pos = [pos[0], pos[1]]
# ball_color = "Red"
def draw(canvas):
for ball_pos in ball_list:
canvas.draw_circle(ball_pos, ball_radius, 1, "Black", ball_color)
# create frame
frame = simplegui.create_frame("Mouse selection", width, height)
frame.set_canvas_background("White")
# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# start frame
frame.start()
list相关操作例3
# Examples of mouse input
import simplegui
import math
# intialize globals
width = 450
height = 300
ball_list = []
ball_radius = 15
# helper function
def distance(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define event handler for mouse click, draw
def click(pos):
changed = False
for ball in ball_list:
if distance([ball[0], ball[1]], pos) < ball_radius:
ball[2] = "Green"
changed = True
if not changed:
ball_list.append([pos[0], pos[1], "Red"])
def draw(canvas):
for ball in ball_list:
canvas.draw_circle([ball[0], ball[1]], ball_radius, 1, "Black", ball[2])
# create frame
frame = simplegui.create_frame("Mouse selection", width, height)
frame.set_canvas_background("White")
# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# start frame
frame.start()
list相关操作例4
注意LIST在循环中不能进行元素删除!!!
注意这个example中在def click(pos)中
在循环中进行了删除和增加。注意删除和增加是分别在两个list中完成的,如果在循环中对同一个list中一边删除一边加入,可能会有问题,如陷入无限循环。
# Examples of mouse input
import simplegui
import math
# intialize globals
width = 450
height = 300
ball_list = []
ball_radius = 15
ball_color = "Red"
# helper function
def distance(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define event handler for mouse click, draw
def click(pos):
remove = []
for ball in ball_list:
if distance(ball, pos) < ball_radius:
remove.append(ball)
if remove == []:
ball_list.append(pos)
else:
for ball in remove:
ball_list.pop(ball_list.index(ball))
def draw(canvas):
for ball in ball_list:
canvas.draw_circle([ball[0], ball[1]], ball_radius, 1, "Black", ball_color)
# create frame
frame = simplegui.create_frame("Mouse selection", width, height)
frame.set_canvas_background("White")
# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# start frame
frame.start()
iteration 各种操作演示
# Iterating over lists
def count_odd(numbers):
count = 0
for num in numbers:
if num % 2 == 1:
count += 1
return count
def check_odd(numbers):
for num in numbers:
if num % 2 == 1:
return True
return False
# 错误用法1 在循环中直接删除元素
def remove_odd(numbers):
for num in numbers:
if num % 2 == 1:
numbers.remove(num)
# 错误用法2 暂存待remove的元素时使用index来表示这些待删的元素
def remove_odd2(numbers):
remove = []
for num in numbers:
if num % 2 == 1:
remove.append(numbers.index(num))
for idx in remove:
numbers.pop(idx)
def remove_odd3(numbers):
remove = []
for num in numbers:
if num % 2 == 1:
remove.append(num)
for num in remove:
numbers.remove(num)
def remove_odd4(numbers):
newnums = []
for num in numbers:
if num % 2 == 0:
newnums.append(num)
return newnums
def remove_last_odd(numbers):
has_odd = False
last_odd = 0
for num in numbers:
if num % 2 == 1:
has_odd = True
last_odd = num
if has_odd:
numbers.remove(last_odd)
def run():
numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22, 93, 48, 76, 15, 7]
print numbers
remove_last_odd(numbers)
print numbers
run()
list comprehension
def square_list1(numbers):
"""Returns a list of the squares of the numbers in the input."""
result = []
for n in numbers:
result.append(n ** 2)
return result
def square_list2(numbers):
"""Returns a list of the squares of the numbers in the input."""
return [n ** 2 for n in numbers]
print square_list1([4, 5, -2])
print square_list2([4, 5, -2])
def is_in_range(ball):
"""Returns whether the ball is in the desired range. """
return ball[0] >= 0 and ball[0] <= 100 and ball[1] >= 0 and ball[1] <= 100
def balls_in_range1(balls):
"""Returns a list of those input balls that are within the desired range."""
result = []
for ball in balls:
if is_in_range(ball):
result.append(ball)
return result
def balls_in_range2(balls):
return [ball for ball in balls if is_in_range(ball)]
print balls_in_range1([[-5,40], [30,20], [70,140], [60,50]])
print balls_in_range2([[-5,40], [30,20], [70,140], [60,50]])
2 Dictionary
2.1 dictionary的定义
注意dictionary的key可以是各种各样的
dict1 = {1:5, "abc":50, True:[ ], 1.7:False, 7.5:"John", 0:"C" }
print dict1 #{True: [], 'abc': 50, 1: 5, 1.7: False, 7.5: 'John', 0: 'C'}
m = list(dict1)
print m #[True, 'abc', 1, 1.7, 7.5, 0]
dict1['a'] = [1,2,3]
dict1['b'] = {}
print dict1 #{True: [], 'abc': 50, 'a': [1, 2, 3], 'b': {}, 1: 5, 1.7: False, 7.5: 'John', 0: 'C'}
#注意
#dict1[{a:1}] = 'a'是错误的。
#只有immutable类型才能做key,任意类型可以做value.
2.2 dictionary
例1造一个编码解码器
# Cipher
import simplegui
CIPHER = {'a': 'x', 'b': 'c', 'c': 'r', 'd': 'm', 'e': 'l'}
message = ""
# Encode button
def encode():
emsg = ""
for ch in message:
emsg += CIPHER[ch]
print message, "encodes to", emsg
# Decode button
def decode():
dmsg = ""
for ch in message:
for key, value in CIPHER.items():
if ch == value:
dmsg += key
print message, "decodes to", dmsg
# Update message input
def newmsg(msg):
global message
message = msg
label.set_text(msg)
# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Cipher", 2, 200, 200)
frame.add_input("Message:", newmsg, 200)
label = frame.add_label("", 200)
frame.add_button("Encode", encode)
frame.add_button("Decode", decode)
# Start the frame animation
frame.start()
例2 造一个编码解码器的改进版
# Cipher
import simplegui
import random
CIPHER = {}
LETTERS = "abcdefghijklmnopqrstuvwxyz"
message = ""
#初始化函数 建造词典
def init():
list_letters=list(LETTERS)
random.shuffle(list_letters) #使用随机生成的词典
for ch in LETTERS:
CIPHER[ch] = list_letters.pop()
# Encode button
def encode():
emsg = ""
for ch in message:
emsg += CIPHER[ch]
print message, "encodes to", emsg
# Decode button
def decode():
dmsg = ""
for ch in message:
for key, value in CIPHER.items():
if ch == value:
dmsg += key
print message, "decodes to", dmsg
# Update message input
def newmsg(msg):
global message
message = msg
label.set_text(msg)
# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Cipher", 2, 200, 200)
frame.add_input("Message:", newmsg, 200)
label = frame.add_label("", 200)
frame.add_button("Encode", encode)
frame.add_button("Decode", decode)
# Start the frame animation
frame.start()
init()
例3 字典版的编码解码器
# Cipher
import simplegui
CIPHER = {'a': 'x', 'b': 'c', 'c': 'r', 'd': 'm', 'e': 'l'}
message = ""
# Encode button
def encode():
emsg = ""
for ch in message:
emsg += CIPHER[ch]
print message, "encodes to", emsg
# Decode button
def decode():
dmsg = ""
for ch in message:
for key, value in CIPHER.items():
if ch == value:
dmsg += key
print message, "decodes to", dmsg
# Update message input
def newmsg(msg):
global message
message = msg
label.set_text(msg)
# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Cipher", 2, 200, 200)
frame.add_input("Message:", newmsg, 200)
label = frame.add_label("", 200)
frame.add_button("Encode", encode)
frame.add_button("Decode", decode)
# Start the frame animation
frame.start()
3 Mouse Input例1 小球随鼠标运动而运动
Mouse input的输入参数是什么?
输入参数是A tuple, (x, y), where x and y are the horizontal and vertical coordinates of the mouse click. 注意tuple的特点是immutable,一旦创建就不能再改变。
# Examples of mouse input
import simplegui
import math
# intialize globals
WIDTH = 450
HEIGHT = 300
ball_pos = [WIDTH / 2, HEIGHT / 2]
BALL_RADIUS = 15
ball_color = "Red"
# helper function
def distance(p, q):
return math.sqrt( (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define event handler for mouse click, draw
def click(pos):
global ball_pos, ball_color
if distance(pos, ball_pos) < BALL_RADIUS:
ball_color = "Green"
else:
ball_pos = list(pos)
ball_color = "Red"
def draw(canvas):
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Black", ball_color)
# create frame
frame = simplegui.create_frame("Mouse selection", WIDTH, HEIGHT)
frame.set_canvas_background("White")
# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# start frame
frame.start()
4 image drawing
image drawing例1 draw a map and it’s magnifier
# Demonstration of a magnifier on a map
import simplegui
# 1521x1818 pixel map of native American language
# source - Gutenberg project
image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg")
# Image dimensions
MAP_WIDTH = 1521
MAP_HEIGHT = 1818
# Scaling factor
SCALE = 3
# Canvas size
CAN_WIDTH = MAP_WIDTH // SCALE
CAN_HEIGHT = MAP_HEIGHT // SCALE
# Size of magnifier pane and initial center
MAG_SIZE = 120
mag_pos = [CAN_WIDTH // 2, CAN_HEIGHT // 2]
# Event handlers
# Move magnifier to clicked position
def click(pos):
global mag_pos
mag_pos = list(pos)
# Draw map and magnified region
def draw(canvas):
# Draw map
canvas.draw_image(image,
[MAP_WIDTH // 2, MAP_HEIGHT // 2], [MAP_WIDTH, MAP_HEIGHT],
[CAN_WIDTH // 2, CAN_HEIGHT // 2], [CAN_WIDTH, CAN_HEIGHT])
# Draw magnifier
map_center = [SCALE * mag_pos[0], SCALE * mag_pos[1]]
map_rectangle = [MAG_SIZE, MAG_SIZE]
mag_center = mag_pos
mag_rectangle = [MAG_SIZE, MAG_SIZE]
canvas.draw_image(image, map_center, map_rectangle, mag_center, mag_rectangle)
# Create frame for scaled map
frame = simplegui.create_frame("Map magnifier", CAN_WIDTH, CAN_HEIGHT)
# register even handlers
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# Start frame
frame.start()