0.Week 3 01 作业心得
此次作业是《笨办法学Python》39-41习题,主要学习内容是列表、字典以及类。
- 从某种程度上来说,列表、字典、类以及元组都是一种数据集,只不过包含的元素方式以及存储方式不一样。
- 列表时多个元素的集合,可以是数字,字母,字符串
- 字典是一系列成对的键值对的结婚,就像锁和钥匙一样成对存在
- 类可以视为一个对象的通用行为的集合,把这种通用行为写成函数表达。比如一个创建一个Dog()类,模拟小狗的通用行为有sit()、eat()、roll_over()等等。当我们下次再写一个金毛犬的行为时,就可以继承DOg()类中所有的通用属性。
- 写注释的好处:一开始学python的时候,只有几行代码,几个行数。学到类的时候就已经有很多个函数了,并且函数与函数之间还有关联。在学习阶段,写注释能够检验自己是否真的读懂了代码。在自己动手实践的时候,也能够让代码段的功能清晰化。
- 习题39 列表的操作
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there's not 10 things in that list,lest's fix that.")
stuff = ten_things.split(' ') # str.split(str="", num=string.count(str)).,通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个字符串
print(stuff) # 打印结果是一个列表,可用来len(stuff)统计文本字数
print(ten_things.split(" ",3)) # 指定前3个元素用" "分隔,其余的作为一个整字符串,也就是说打印结果的列表中有3+1个元素
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
while len(stuff) != 10:
next_one = more_stuff.pop() # list.pop(),弹出[-1]位置元素,函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
print("Adding: ",next_one)
stuff.append(next_one) # 将next_one加入到stuff列表中
print("There's %d items now." % len(stuff))
print("There we go: ", stuff) # 字符串+列表
print("Let's do some things with stuff.")
print(stuff[1]) # 列表的位置索引从0开始,倒数的话从-1开始
print(stuff[-1]) # 打印列表最后一个元素
print(stuff.pop()) # 删除列表的最后一个元素并打印,这个列表已被更改
print(' '.join(stuff)) # join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。str.join(sequence),并返回通过指定字符连接序列中元素后生成的新字符串。
print('#'.join(stuff[3:5])) # 指定在stuff[3:5]之间插入一个#字符并输出
- 习题40 字典,可爱的字典
# 代码段1
things = ['a', 'b', 'c', 'd'] # 列表以[]包含元素,元素与元素之间用,隔开,位置索引从0开始
print(things[1]) # 列表元素读取:'b'
things[1] = 'z' # 列表元素修改:对things列表进行修改,指定位置索引,以及需要传递的字符串
print(things)
stuff = {'name': 'Zed', 'age': 36, 'height': 6 * 12 + 2} # 字典由成对的键值对组成,键与值之间以冒号:分隔,键值对与键值对之间以逗号分隔,用花括号包含所有的键值对
print(stuff)
print(stuff['name']) # 指定key,获取与之成对的value值,dic_name[key_name],方括号内指定键的名称
print(stuff['age'])
print(stuff['height'])
stuff['city'] = "San Francisco" # 添加新的键值对,dic_name[new_key_name] = new_value
print(stuff['city'])
stuff[1] = "Wow" # 添加新的键值对
stuff[2] = "Neato"
print(stuff[1])
print(stuff[2])
print(stuff) # 打印列表
del stuff['city'] # 删除字典键值对:del dic_name[key_name],指定键名,删除一对键值对
del stuff[1]
del stuff[2]
# for循环遍历一个字典的所有键值对
for key,value in stuff.items():
print(key, ":", value)
# 代码段2
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonvile'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
cities['_find'] = find_city #为cities这个字典添加一个'_find'的键,其值为一个函数find_city.调用cities['_find'](something)就相当于find_city(something).
while True:
print("State? (Enter to quit)")
state = input("> ")
if not state:
break
city_found = cities['_find'](cities, state) # 这个代码不太好理解,尤其是括号里的两个参数要多多理解
print(city_found)
- 习题41 来自 Percal 25 号行星的哥顿人(Gothons)
from sys import exit # 从sys模组导入exit函数
from random import randint # 从random模组导入randint()函数,用于生成随机数
# 定义一个death()函数,输出quips列表中的随机一个元素,并终止程序
def death():
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a luser.",
"I have a small puppy that's better at this."]
print(quips[randint(0, len(quips) - 1)])
exit(1)
# 定义一个central_corridor()函数,打印文本。然后根据输入内容在if-elif-else语句中进行选择判断,选择其中的符合输入条件的代码执行
# 每一个选择分支,都执行一个打印任务,然后再返回接着执行的一个代码段。
def central_corridor():
print("The Gothons of Planet Percal #25 have invaded your ship and destroyed")
print("your entire crew. You are the last surviving member and your last")
print("mission is to get the neutron destruct bomb from the Weapons Armory,")
print("put it in the bridge, and blow the ship up after getting into an ")
print("escape pod.")
print("\n")
print("You're running down the central corridor to the Weapons Armory when")
print("a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume")
print("flowing around his hate filled body. He's blocking the door to the")
print("Armory and about to pull a weapon to blast you.")
action = input("> ")
if action == "shoot!":
print("Quick on the draw you yank out your blaster and fire it at the Gothon.")
print("His clown costume is flowing and moving around his body, which throws")
print("off your aim. Your laser hits his costume but misses him entirely. This")
print("completely ruins his brand new costume his mother bought him, which")
print("makes him fly into an insane rage and blast you repeatedly in the face until")
print("you are dead. Then he eats you.")
return 'death'
elif action == "dodge!":
print("Like a world class boxer you dodge, weave, slip and slide right")
print("as the Gothon's blaster cranks a laser past your head.")
print("In the middle of your artful dodge your foot slips and you")
print("bang your head on the metal wall and pass out.")
print("You wake up shortly after only to die as the Gothon stomps on")
print("your head and eats you.")
return 'death'
elif action == "tell a joke":
print("Lucky for you they made you learn Gothon insults in the academy.")
print("You tell the one Gothon joke you know:")
print("Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr.")
print("The Gothon stops, tries not to laugh, then busts out laughing and can't move.")
print("While he's laughing you run up and shoot him square in the head")
print("putting him down, then jump through the Weapon Armory door.")
return 'laser_weapon_armory'
else:
print("DOES NOT COMPUTE!")
return 'central_corridor'
# 定义一个laser_weapon_armory()函数,执行打印任务,以随机生成的三个数字组成的code与用户输入值guess之间的比较,并以guesses计数
# guesses初始值设置为0,当guess值与code值符合while条件时,在while循环中递增guesses,并将guess值重置为新的用户输入值
# if判断句,执行打印任务并返回需要继续执行的任务程序
def laser_weapon_armory():
print("You do a dive roll into the Weapon Armory, crouch and scan the room")
print("for more Gothons that might be hiding. It's dead quiet, too quiet.")
print("You stand up and run to the far side of the room and find the")
print("neutron bomb in its container. There's a keypad lock on the box")
print("and you need the code to get the bomb out. If you get the code")
print("wrong 10 times then the lock closes forever and you can't")
print("get the bomb. The code is 3 digits.")
code = "%d%d%d" % (randint(1, 9), randint(1, 9), randint(1, 9))
guess = input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print("BZZZZEDDD!")
guesses += 1
guess = input("[keypad]> ")
if guess == code:
print("The container clicks open and the seal breaks, letting gas out.")
print("You grab the neutron bomb and run as fast as you can to the")
print("bridge where you must place it in the right spot.")
return 'the_bridge'
else:
print("The lock buzzes one last time and then you hear a sickening")
print("melting sound as the mechanism is fused together.")
print("You decide to sit there, and finally the Gothons blow up the")
print("ship from their ship and you die.")
return 'death'
def the_bridge():
print("You burst onto the Bridge with the neutron destruct bomb")
print("under your arm and surprise 5 Gothons who are trying to")
print("take control of the ship. Each of them has an even uglier")
print("clown costume than the last. They haven't pulled their")
print("weapons out yet, as they see the active bomb under your")
print("arm and don't want to set it off.")
action = input("> ")
if action == "throw the bomb":
print("In a panic you throw the bomb at the group of Gothons")
print("and make a leap for the door. Right as you drop it a")
print("Gothon shoots you right in the back killing you.")
print("As you die you see another Gothon frantically try to disarm")
print("the bomb. You die knowing they will probably blow up when")
print("it goes off.")
return 'death'
elif action == "slowly place the bomb":
print("You point your blaster at the bomb under your arm")
print("and the Gothons put their hands up and start to sweat.")
print("You inch backward to the door, open it, and then carefully")
print("place the bomb on the floor, pointing your blaster at it.")
print("You then jump back through the door, punch the close button")
print("and blast the lock so the Gothons can't get out.")
print("Now that the bomb is placed you run to the escape pod to")
print("get off this tin can.")
return 'escape_pod'
else:
print("DOES NOT COMPUTE!")
return "the_bridge"
def escape_pod():
print("You rush through the ship desperately trying to make it to")
print("the escape pod before the whole ship explodes. It seems like")
print("hardly any Gothons are on the ship, so your run is clear of")
print("interference. You get to the chamber with the escape pods, and")
print("now need to pick one to take. Some of them could be damaged")
print("but you don't have time to look. There's 5 pods, which one")
print("do you take?")
good_pod = randint(1, 5)
guess = input("[pod #]> ")
if int(guess) != good_pod:
print("You jump into pod %s and hit the eject button." % guess)
print("The pod escapes out into the void of space, then")
print("implodes as the hull ruptures, crushing your body")
print("into jam jelly.")
return 'death'
else:
print("You jump into pod %s and hit the eject button." % guess)
print("The pod easily slides out into space heading to")
print("the planet below. As it flies to the planet, you look")
print("back and see your ship implode then explode like a")
print("bright star, taking out the Gothon ship at the same")
print("time. You won!")
exit(0) #
# 以字段:函数作为键值对,存入ROOMS字典
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
# 定义一个runner()的函数,需要指定map,start两个参数。
def runner(map, start): # 注释,理解
next = start
while True:
room = map[next] # map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
print("\n--------")
next = room()
runner(ROOMS, 'central_corridor')
- 习题 42 物以类聚
from sys import exit
from random import randint
class Game(object):
'''一次模拟游戏的类'''
def __init__(self, start):
'''初始化属性start'''
self.quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a luser.",
"I have a small puppy that's better at this."
] # 设置quips默认值为一个非空列表
self.start = start # 获取储存在形参start中的值,并将其存储到变量start中
def play(self):
next = self.start # 传递实参start给next变量
while True:
print("\n--------")
room = getattr(self, next)
next = room()
def death(self):
print(self.quips[randint(0, len(quips) - 1)])
exit(1)
'''''
a_game = Game("central_corridor")
a_game.play()
网友评论