Learn Python The Hard Way学习(38) - 列表操作

我们已经学习过list了,在学习while的时候我们给列表添加元素,并且打印它们。在加分练习中也让我们找出list的一些其它操作,如果你不知道我在说什么,那么回去复习一下我们学过的东西吧。

如果我们只知道使用list的append方法,那么我们还不是真正知道这个函数的用法,让我们来看看它的使用方法吧。

当我们使用mystuff.append('hello')的时候发生了一系列的事情,让我们看看到底发生了什么:
  1. python会先查看mystuff变量,看看是不是函数的参数,或者是全局变量,反正先要找到mystuff。
  2. 当mystuff使用 . 号的时候,会先看mystuff这个变量是什么,如果是list的话,会有很多它的方法可以使用。
  3. 使用append的时候,会去查找mystuff是不是有’append‘这个名称,有的话就直接拿来使用。
  4. 如果append后面有圆括号,那么就知道它是一个函数,像平时一样执行这个函数就好了,还会有额外的参数。
  5. 这个额外的参数就是mystuff,奇怪吧,但是python就是这样做的,最后函数是这样的:append(mystuff, 'hello')。
大多数情况下你不必知道这是怎么回事,但是在你遇到下面这个错误的时候就有帮助了:
root@he-desktop:~# python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object):
...     def test(hi):
...             print "hi"
... 
>>> a = Thing()
>>> a.test("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (2 given)
>>> 

上面这些是什么?你没学习过class,不过后面一点我们就要学习到了。现在我们看看python报的这个错,如果我们改成test(a, "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 "Thing'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])


运行结果
root@he-desktop:~/mystuff# python ex38.py 
Wait there's not 10 things in that list, let's fix that.
Adding: Boy
Thing's 7 items now.
Adding: Girl
Thing's 8 items now.
Adding: Banana
Thing's 9 items now.
Adding: Corn
Thing'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
root@he-desktop:~/mystuff# 

加分练习
1. 把函数翻译成python执行的样子,比如' '.join(stuff)是join(' ', stuff)

2. 用语言翻译两张函数调用方法,比如' '.join(stuff)是用' '连接stuff,join(' ', stuff)就是用' '和stuff调用join方法

3. 上网查一些面向对象编程的信息,晕了吧,我以前也是,不用担心,以后会慢慢了解的。

4. 查一下python中class的用法,不要看其他语言的class用法,这样只会混淆你。

5. dir(something)和something的class有什么关系。

6. 如果你不懂我说什么,没关系,程序员发明了面向对象编程这个东西,简称OOP,并且经常使用,如果你觉得这个很难,那么我们学习函数编程。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值