书上的代码没注释,且有一点点错误,所以发文
import turtle
def convert(point):
#当前点的X,Y坐标
lon = point[0]
lat = point[1]
#为理清思路,所有分两步进行
x = mapWidth - (maxX - lon) * xRadio
y = mapHeight -(maxY - lat) * yRadio
x = x - (mapWidth / 2)
y = y - (mapHeight / 2)
return [x, y]
if __name__ == "__main__":
#列表坐标初始化
name, points, pop= 0, 1, 2
state = ['COLORADO', [[-109, 37], [-109, 41], [-102, 41], [-102, 37]], 5187582]
cities = []
cities.append(['DENVER', [-104.98, 39.74], 634265])
cities.append(['BOULDER', [-105.27, 40.02], 98889])
cities.append(['DURANGO', [-107.88, 37.28], 17039])
#设置画布大小
mapWidth = 400
mapHeight = 300
turtle.screensize(canvwidth=mapWidth, canvheight=mapHeight, bg=None)
#若所在值大于最大值,则替换,其它类同
minX = 180
maxX = -180
minY = 90
maxY= -90
for x, y in state[points]:
if x < minX: minX = x
elif x > maxX: maxX = x
if y < minY: minY = y
elif y > maxY: maxY = y
#获取画布/方框的比值
distX = maxX - minX
distY = maxY - minY
xRadio = mapWidth / distX
yRadio = mapHeight / distY
#提笔
turtle.up()
firstPixel = None
#绘制方框
for point in state[points]:
#调用convert函数,获取画布点
pixel = convert(point=point)
#存放首地址
if not firstPixel:
firstPixel = pixel
#移动
turtle.goto(pixel)
#落笔
turtle.down()
turtle.goto(firstPixel)
turtle.up()
turtle.goto([0, 0])
#写下姓名
turtle.write(state[name], align='center', font=('Arial', 16, 'bold'))
for city in cities:
pixel = convert(city[points])
turtle.up()
turtle.goto(pixel)
turtle.dot(10)
turtle.write(f'{city[name]}, Pop.:{city[pop]}', align='left')
turtle.up()
#标出入口最大的城市
biggestCity = max(cities, key=lambda city: city[pop])
turtle.goto(0, -200)
turtle.write(f'The biggest city is:{biggestCity[name]}')
#标出离西方最远的城市
westernCity = min(cities, key=lambda city: city[points])
turtle.goto(0, -220)
turtle.write(f'The western-most city is:{westernCity[name]}')
turtle.done()
#布置画布,canvwidth设置画布宽度, canvheight设置画布高度
- turtle.screensize(canvwidth=mapWidth, canvheight=mapHeight, bg=None)
#提笔
- turtle.up()
#移动(移动到画布上的(x, y)点处)
- turtle.goto(x, y)
#下笔
- turtle.down()
#画点(直径为10个像素点)
- turtle.dot(10)
#写字(‘字符串’, align=‘文字位置’, font=('字体, 大小, ‘加粗’))
- turtle.write(‘hello world’, align=‘center’, font=(‘Arial’, 16, ‘bold’))
#隐藏画笔
- turtle.pen(shown = False)
#保持画布打开状态(没有这条语句,画完就闪退了)
- turtle.done()
lambda相当于匿名函数,没有名称的函数。
例如:city为形参,city[pop]为return值
代码含义:将cities列表的第三项 人数 来作比较,返回第三项最大的子列表
- biggestCity = max(cities, key=lambda city: city[pop])