LearnPython3theHardWay__Excercise 38 Doing Things to Lists

字符串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
  1. 要理解调用过的函数并知道它是干什么用的,如 list.pop()
  2. 上网看看面向对象编程,不管你看不看得懂
  3. 看python文档里的类
  4. 不懂类,没关系。类只是程序员想让自己看起来比较聪明比较专业才发明出来的。你觉得很难,就用函数式编程
  5. 在生活中找1个0适合运用列表的例子,并尝试写代码
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值