字符串split(),join(),列表的方法,append,pop
作者开始先讲了下列表的处理过程 mystuff.append(‘hello’),我们都知道这句话的意思是给mystuff这个列表添加’hello’这个元素到列表的尾端。python先找出 mystuff ,然后看到 mystuff后面的一个小句号 . ,知道mystuff有许多方法。然后找到append方法,看到有括号,就看后面的参数并调用它
大多数情况下,我们不需要知道发生了什么事,但我可以从python给出的错误中得到提示。
例如:
class Thing(object):
def test(message):
print(message)
a = Thing()
a.test('hello')
===========result===========
Traceback (most recent call last):
File "practest.py", line 6, in <module>
a.test('hello')
TypeError: test() takes 1 positional argument but 2 were given
这是类,还没学过,先带着问题继续。我们可以看到错误提示就知道哪里出错了
开始练习
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are 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(f"There are {len(stuff)} items now.")
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!
What you should see
Wait there are not 10 things in that list. let's fix that.
Adding: Boy
There are 7 items now.
Adding: Girl
There are 8 items now.
Adding: Banana
There are 9 items now.
Adding: Corn
There are 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
列表有很多用途。什么时候使用列表?你需要有顺序的时候,需要可以用数字随便访问内容的时候和用for的时候。
Study Drills
- 要理解调用过的函数并知道它是干什么用的,如 list.pop()
- 上网看看面向对象编程,不管你看不看得懂
- 看python文档里的类
- 不懂类,没关系。类只是程序员想让自己看起来比较聪明比较专业才发明出来的。你觉得很难,就用函数式编程
- 在生活中找1个0适合运用列表的例子,并尝试写代码