《笨办法学python》加分习题39——我的答案

这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

原文例题:

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print "Wait there's not 10 things in that list, let's fix that."

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
    next_one = more_stuff.pop()
    print "Adding: ", next_one
    stuff.append(next_one)
    print "There's %d items now." % len(stuff)

print "There we go: ", stuff

print "Let's do some things with stuff."

print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!

习题答案:

1、

stuff = ten_things.split(' ') # split('', ten_things)

next_one = more_stuff.pop() # pop(more_stuff)

stuff.append(next_one) # append(next_one, stuff)

print stuff.pop() # pop(stuff)

print ' '.join(stuff) # what? cool! join(stuff, ' ')

print '#'.join(stuff[3:5]) # super stellar! join(stuff[3:5], '#')

2、

# 用‘ ’拆开ten_things;为‘ ’和ten_things调用了split函数
stuff = ten_things.split(' ') # split('', ten_things)
# 提取出more_stuff中-1位元素并打印出来;为more_stuff[-1]位调用pop函数
next_one = more_stuff.pop() # pop(-1,more_stuff)
# 添加next_one到stuff中;为next_one和stuff调用append函数
stuff.append(next_one) # append(next_one, stuff)
# 类似如上pop()
print stuff.pop() # pop(-1,stuff)
#如习题答案
print ' '.join(stuff) # what? cool! join(stuff, ' ')
#类似习题答案
print '#'.join(stuff[3:5]) # super stellar! join(stuff[3:5], '#')

4、类
5、dir(something)中,dir()在pydoc的解释如下:

Help on built-in function dir in module builtin:
dir(…)
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.

看了下,大概是如果something有定义dir这个方法的话就调用这个方法,如果没有就返回something所在类的其他方法名称。

你可能感兴趣的:(《笨办法学python》加分习题39——我的答案)