学习Python编程第010天

今天把第四章看完了,虽然看懂了大部份,但就是不知道应该应用在哪些方面。

先把一些代码打一遍,巩固一下。

>>> [1,2,3]  #列表可以是整数

[1, 2, 3]

>>> ['cat','bat','rat','elephant']  #列表可以是字符串

['cat', 'bat', 'rat', 'elephant']

>>> ['hello',3.1415,True,None,42]  #列表可以是字符串和浮点数、整数,还可以是值。

['hello', 3.1415, True, None, 42]

>>> [hello]  #列表不可以是一个没有定义过的变量

Traceback (most recent call last):

  File "<pyshell#3>", line 1, in <module>

    [hello]

NameError: name 'hello' is not defined

>>> spam=['cat', 'bat', 'rat', 'elephant']  #列表可以赋值给变量

>>> spam

['cat', 'bat', 'rat', 'elephant']

>>> spam=[['cat','bat'],[10,20,30,40,50]]  #列表里可以包含多个列表

>>> spam[0]  #调用第一个列表值

['cat', 'bat']

>>> spam[0][1]  #调用第1个列表值里的第2个值

'bat'

>>> spam[1][3]  #调用第2个列表值里的第4个值

40

>>> spam=['cat', 'bat', 'rat', 'elephant']

>>> spam[-1]  #调用表列中的最后一个下标

'elephant'

>>> spam[-3]  #调用表列中倒数第3个下标

'bat'

>>> 'The '+spam[-1]+' is afraid of the '+spam[-3]+'.'

'The elephant is afraid of the bat.'

>>> spam=['cat', 'bat', 'rat', 'elephant']

>>> spam[0:4]  #切片是第一个数到第4个数

['cat', 'bat', 'rat', 'elephant']

>>> spam[1:3]  #切片是第2个数到第3个数

['bat', 'rat']

>>> spam[0:-1]  #切片是第1个数到倒数第2个数

['cat', 'bat', 'rat']

>>> spam[0:-2]  #切片是第1个数到倒数第3个数

['cat', 'bat']

>>> spam[0:-3]  #切片是第1个数到倒数第4个数

['cat']

>>> spam[2:-3]  #切片是第3个数到倒数第4个数,

[]  #因为不存在,所以是空的

>>> spam=['cat', 'bat', 'rat', 'elephant']

>>> spam[:2]  #省略第一个下标,相当于使用0

['cat', 'bat']

>>> spam[1:]  #省略第二个下标,相当于使用列表的长度

['bat', 'rat', 'elephant']

>>> spam[:]  #两个都省略,表示整个列表

['cat', 'bat', 'rat', 'elephant']

>>> spam=['cat', 'bat', 'rat', 'elephant']

>>> len(spam)  #返回列表中值的个数

4

>>> spam=['cat', 'bat', 'rat', 'elephant']

>>> spam[0]='aardvark'  #可以通过赋值语句,改变列表里对应的值

>>> spam

['aardvark', 'bat', 'rat', 'elephant']

>>> spam[3]=spam[1]  #列表里的值,也可以用来改变其他位置的值

>>> spam

['aardvark', 'bat', 'rat', 'bat']

>>> spam[-1]=123456  #也可以用整数替换字符串

>>> spam

['aardvark', 'bat', 'rat', 123456]

重新打了一遍代码,感觉对这些概念又进一步熟悉了很多。所以学习的过程不能只看,一定要动手,一定要多打代码。这样才可以学得更好。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容