Python入门记——列表1

来源:互联网 发布:微博营销软件下载 编辑:程序博客网 时间:2024/05/13 21:47

一个简单的电影列表:

>>> movies=["the holy grail","the life of brian","the meaning of life"]
4个步骤:
1、数据加引号,转换为字符串;
2、用逗号将各项隔开;
3、列表两边加上表示开始和结束的中括号;
4、使用赋值操作符(=)将列表赋至一个标识符(movies)。
Python的变量标识符没有类型。
Python不需要知道数据项的类型,它需要知道的只是你需要一个列表,并给它起了个名字,且其中包含了一些数据项。
创建列表原理:在Python中创建一个列表时,解释器会在内存中创建一个类似数组的数据结构来存储数据,数据项从下往上堆放,形成一个堆栈。
访问一个列表槽中的数据项时,使用标准的中括号偏移量记法即可。
>>> print(movies[1])the life of brian
使用len() 可以计算出列表中的数据项个数:

>>> print(len(movies))
3


使用append()在列表末尾增加一项;使用pop()从末尾删除一项;使用extend()在末尾增加一个数据项集合:

>>> movies.append("new movie1")
>>> print(movies)
['the holy grail', 'the life of brian', 'the meaning of life', 'new movie1']
>>> 

>>> movies.pop()
'new movie1'
>>> print(movies)
['the holy grail', 'the life of brian', 'the meaning of life']
>>> 

>>> movies.extend(["new1","new2"])
>>> print(movies)
['the holy grail', 'the life of brian', 'the meaning of life', 'new1', 'new2']
>>> 


使用remove()删除指定项;使用insert()在某个特定位置增加一项:

>>> movies.remove("new1")
>>> print(movies)
['the holy grail', 'the life of brian', 'the meaning of life', 'new2']
>>> 
>>> movies.insert(1,"new1")
>>> print(movies)
['the holy grail', 'new1', 'the life of brian', 'the meaning of life', 'new2']
>>> 


Python列表可以包含混合类型的数据。



迭代处理:


for循环迭代示例:(注意下方缩进,python很注重缩进、对齐这些。强迫症福音)

>>> for a in movies:
      print(a)


the holy grail
1975
new1
the life of brian
the meaning of life
new2
>>> 


使用for循环时,不需要定义一个i然后i++,直接任意print一个目标标识符,它会自己完成,打印出所有项。

原理:迭代处理时,会将列表中的各个数据值依次分别赋至目标标识符,因此每循环一下,目标标识符都会指示一个不同的数据值。循环迭代至处理完所有数据。


for循环是可伸缩的,适用于任意大小的列表。



while循环与for有着同样的作用。通常能用for就用for,特殊情况不得已才使用while。

使用while时就需要自己考虑“状态信号”,需要使用计数标识符(同样需要注意缩进和对齐):

>>> while count< len(movies):
        print(movies[count])
        count=count+1



the holy grail
1975
new1
the life of brian
the meaning of life
new2
>>>