说明:
Python内置的数据类型有:列表(list)、字典(dictionary)、元组(tuple)、字符串(string)、集合(set)
本次重点:
Python操作列表、字典、元组
一、列表(list)
1.特性:list是一种有序的集合,可以随时添加和删除其中的元素。
2.创建:一对方括号“[]”和其包含的元素,单个元素可以不加逗号,同元组一样,可以创建嵌套列表。如:
tempList = ["one","two","three"]
#列表元素可以是不同数据类型的
L = ['Apple', 123, True]
3.基本操作及方法:
总结:
方法 | 描述 |
---|---|
list.append(x) | 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x] |
详解:
(1)访问:
3.1.1 访问一般列表
用索引来访问list中每一个位置的元素,记得索引是从0开始的:
>>> tempList [0]
'one'
>>> tempList [1]
'two'
>>> tempList [2]
'three'
>>> tempList [3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(tempList ) -