一、list概述
list (列表)是python中最常用的数据类型之一,通过列表可以对数据实现最方便的存储,修改等操作。在python3中,list支持如下方法:
Help on class list in module builtins: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable‘s items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value.n | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | L.__reversed__() -- return a reverse iterator over the list | | __rmul__(self, value, /) | Return self*value. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | L.__sizeof__() -- size of L in memory, in bytes | | append(...) | L.append(object) -> None -- append object to end | | clear(...) | L.clear() -> None -- remove all items from L | | copy(...) | L.copy() -> list -- a shallow copy of L | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -> None -- extend list by appending elements from the iterable | | index(...) | L.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | insert(...) | L.insert(index, object) -- insert object before index | | pop(...) | L.pop([index]) -> item -- remove and return item at index (default last). | Raises IndexError if list is empty or index is out of range. | | remove(...) | L.remove(value) -> None -- remove first occurrence of value. | Raises ValueError if the value is not present. | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
二、list操作
- 定义列表
定义一个列表很简单,使用[]括号将元素包裹起来即可,元素与元素之间使用‘,’分隔。
1 names = [‘liu‘, ‘shi‘, ‘yi‘, 10, 27]
- 访问列表
访问列表使用下标访问,下标从0开始计数。访问列表中的元素有多种访问方式:正取,倒取。
>>> names = [‘liu‘, ‘shi‘, ‘yi‘, 10, 27] >>> names[1] ‘shi‘ >>> names[3] 10 >>> names[-1] 27 >>> names[-2] # 还可以倒着取 10
- 修改列表
修改列表直接通过列表的下标对其对应的值进行修改即可。
>>> names [‘liu‘, ‘test‘, ‘yi‘, 10, 27] >>> names[-2] = ‘test1‘ >>> names [‘liu‘, ‘test‘, ‘yi‘, ‘test1‘, 27]
- 删除列表
删除列表有多种删除方式,可以通过del关键字、remove()方法,pop()方法对列表中的元素进行删除。
>>> names [‘liu‘, ‘test‘, ‘yi‘, ‘test1‘, 27] >>> del names[0] # 通过del关键字删除指定下标的元素 >>> names [‘test‘, ‘yi‘, ‘test1‘, 27] >>> del names[-1] >>> names [‘test‘, ‘yi‘, ‘test1‘] >>> names.remove(‘test1‘) # 通过remove方法删除指定的元素 >>> names [‘test‘, ‘yi‘] >>> names.pop() # 弹出并删除最后一个元素 ‘yi‘ >>> names.pop(-1) # 弹出并删除指定位置的元素 ‘test‘ >>> names [] >>> del names # 删除整个列表 >>> names Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘names‘ is not defined
list中的pop方法要格外的注意,该方法具有弹出和删除两个特性,在删除指定的元素的同时会返回该元素。
三、列表支持的特性
- 切片特性
list除了支持一次获取单个元素的特性以外,还支持一次获取多个元素,获取的多个元素以list的形式返回。
>>> names = [‘liu‘, ‘shi‘, ‘yi‘, 10, 27] >>> names[1:4] [‘shi‘, ‘yi‘, 10] >>> names[1:-1] [‘shi‘, ‘yi‘, 10] >>> names[1:] [‘shi‘, ‘yi‘, 10, 27] >>> names[:3] [‘liu‘, ‘shi‘, ‘yi‘] >>> names[1:] [‘shi‘, ‘yi‘, 10, 27] >>> names[::2] [‘liu‘, ‘yi‘, 27]
list的切片特性如下:
list[起始元素:终止元素:步长],切片后返回的list不包含终止元素,步长默认为1。
- 追加特性
list可以在其最后使用append方法追加一个元素
>>> names.append(‘test‘) >>> names [‘liu‘, ‘shi‘, ‘yi‘, 10, 27, ‘test‘]
- 插入特性
list除了在其最后追加元素之外,还可以在指定位置插入元素,使用insert()方法追加元素。
>>> names.insert(1,‘hello world‘) >>> names [‘liu‘, ‘hello world‘, ‘shi‘, ‘yi‘, 10, 27, ‘test‘]
- 扩展特性
所谓的扩展是将两个list合并到一起,但是和“+”操作符是有区别的。
>>> a = [1,2,3] >>> b = [4,5,6] >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6] >>> a + b [1, 2, 3, 4, 5, 6, 4, 5, 6] >>> a [1, 2, 3, 4, 5, 6]
extend()方法会修改list,而+不会修改,仅仅返回+之后的结果。
- 统计特性
list中的count方法可以统计出某个元素出现的次数
>>> names.count(10)
1
- 翻转特性
使用reverse()方法可以对list中的元素进行翻转
>>> names.reverse() >>> names [‘test‘, 27, 10, ‘yi‘, ‘shi‘, ‘hello world‘, ‘liu‘]
- 获取下标
使用index()方法,获取某个元素的下标。
>>> names.index(27)
1
四、元组
元组其实和列表差不多,也是存放一组数据,只不过是它一旦创建,便不能修改,所以又叫只读列表。
class tuple(object) | tuple() -> empty tuple | tuple(iterable) -> tuple initialized from iterable‘s items | | If the argument is a tuple, the return value is the same object. | Return self==value. | Methods defined here: | __ge__(self, value, /) | __add__(self, value, /) | Return self+value. | __getattribute__(self, name, /) | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(...) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value.n | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return self*value. | | count(...) | T.count(value) -> integer -- return number of occurrences of value | | index(...) | T.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present.
元组仅有两个方法,count和index。