目标:

理解列表方法的真实含义。

操作:

list_1.append(element) ==> append(list_1, element)

mystuff.append('hello') 这样的代码时,你事实上已经在Python 内部激发了一个连锁反应。以下是它的工作原理:

1. 先找到mystuff 这个变量

2. 找到了mystuff ,再处理句点. (period) 这个操作符,开始查看mystuff 内部的一些变量了。由于mystuff 是一个列表,Python 知道mystuff 支持一些函数。

3. 接下来轮到了处理append 。Python 会将“append” 和mystuff 支持的所有函数的名称一一对比,如果确实其中有一个叫append 的函数,那么Python 就会去使用这个函数。

4. 接下来Python 看到了括号( (parenthesis) 并且意识到, “噢,原来这应该是一个函数”,到了这里,它就正常会调用这个函数了,不过这里的函数还要多一个参数才行。

5. 这个额外的参数其实是mystuff! 我知道,很奇怪是不是?不过这就是Python 的工作原理,所以还是记住这一点,就当它是正常的好了。真正发生的事情其实是append(mystuff, 'hello') ,不过你看到的只是mystuff.append('hello')

代码:

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])
print(stuff.pop())
print(' '.join(stuff))
print("#".join(stuff[3:5]))

结果:

Wait there's not 10 things in that list, let's fix that.
Adding:  Boy
There's 7 items now.
Adding:  Girl
There's 8 items now.
Adding:  Banana
There's 9 items now.
Adding:  Corn
There's 10 items now.
There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light

注释:

  • 将每一个被调用的函数以上述的方式翻译成Python 实际执行的动作。

例如:' '.join(things) 其实是join(' ', things) 。

  • 将这两种方式翻译为自然语言。

例如,'  '.join(things) 可以翻译成“用1个空格连接(join) things”,而join('  ', things) 的意思是“为一个空格(' ')和things 调用join函数”。这其实是同一件事情。

学自《笨办法学Python》

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!