列表学习。
List是python中的基本数据结构之一。创建一个列表的方法
L = [1,2,3,'a']
通过help(list)查看列表的属性及方法。
>>> help(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() -> new empty list 新建一个空的列表
In [1]: a = list()
In [2]: a
Out[2]: []
list(iterable) -> new list initialized from iterable's items
将可迭代的items转换为列表,例如字符串和元组
In [6]: s = "hello world!"
In [7]: L = list(s)
In [8]: L
Out[8]: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
__add__(self, value, /) Return self+value.列表相加
In [1]: a = [1,2]
In [2]: b = [1,2]
In [3]: a.__add__(b) # 返回a+b,a,b本身没有改变
Out[3]: [1, 2, 1, 2]
In [4]: a
Out[4]: [1, 2]
In [5]: b
Out[5]: [1, 2]
In [6]: c = a.__add__(b)
In [7]: c
Out[7]: [1, 2, 1, 2]
In [8]: d = a+b
In [9]: c == b
Out[9]: False
In [10]: c == d
Out[10]: True
__contains__(self, key, /) Return key in self. 判断列表是否包含某对象
In [11]: L = [1,2,3,4]
In [12]: L.__contains__(1)
Out[12]: True
In [13]: L.__contains__(2)
Out[13]: True
In [14]: L.__contains__(0)
Out[14]: False
In [15]: L.__contains__('a')
Out[15]: False
In [16]: L.__contains__(L) #并不包含本身
Out[16]: False
In [18]: L in L
Out[18]: False
In [19]: 2 in L
Out[19]: True
In [20]: 0 in L
Out[20]: False
__delitem__(self, key, /) Delete self[key]. 删除某对象
In [21]: L = [1,2,3]
In [22]: L.__delitem__(0) #删除第0个对象
In [23]: L
Out[23]: [2, 3]
In [24]: del L[1] #删除第1个对象
In [25]: L
Out[25]: [2]
__eq__(self, value, /) Return self==value. 判断列表是否等于某列表
In [36]: a = [1,2,3,4]
In [37]: b = [1,2]
In [38]: a.__eq__(1)
Out[38]: NotImplemented #没有实现该功能
In [39]: a.__eq__([1,2])
Out[39]: False
In [40]: a.__eq__(b)
Out[40]: False
In [41]: a.__eq__([1,2,3,4])
Out[41]: True
In [42]: a.__eq__((1,2,3,4))
Out[42]: NotImplemented
与 == 略有差异
In [43]: a = [1,2,3,4]
In [44]: b = [1,2]
In [45]: a == 1
Out[45]: False
In [46]: a == [1,2]
Out[46]: False
In [47]: a == [1,2,3,4]
Out[47]: True
In [48]: a == b
Out[48]: False
In [49]: a == (1,2,3,4)
Out[49]: False
__ge__(self, value, /) Return self>=value.判断列表是否不小于某列表。与__eq__类似
__getattribute__(self, name, /) Return getattr(self, name).
In [63]: a = [1,2,3,4]
In [64]: a.__getattribute__('__len__')
Out[64]: <method-wrapper '__len__' of list object at 0x02558EE0>
In [65]: b = a.__getattribute__('__len__')
In [66]: b()
Out[66]: 4
In [67]: a
Out[67]: [1, 2, 3, 4]
In [68]: a.__getattribute__('copy')
Out[68]: <function list.copy>
In [69]: b = a.__getattribute__('copy')
In [70]: c = b()
In [71]: c
Out[71]: [1, 2, 3, 4]
__getitem__(...) x.__getitem__(y) <==> x[y] #返回某索引下的对象
In [1]: a = [1,2,3,"hello",(1,2,3)]
In [2]: a.__getitem__(0)
Out[2]: 1
In [3]: a.__getitem__(3)
Out[3]: 'hello'
In [4]: a.__getitem__(4)
Out[4]: (1, 2, 3)
In [5]: a.__getitem__(5) 无法访问越界的对象
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-5-3a58e3eacf6a> in <module>()
----> 1 a.__getitem__(5)
IndexError: list index out of range #越界报错
In [6]: a = [1,2,3,"hello",(1,2,3)]
In [7]: a[0]
Out[7]: 1
In [8]: a[3]
Out[8]: 'hello'
In [9]: a[4]
Out[9]: (1, 2, 3)
In [10]: a[5]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-10-b6a934feab86> in <module>()
----> 1 a[5]
IndexError: list index out of range
__gt__(self, value, /) Return self>value. 判断列表是否大于某列表。与__eq__类似
__iadd__(self, value, /) Implement self+=value. self+=value value可以是任何可迭代对象。
In [3]: a = [1,2,3,4]
In [4]: a.__iadd__("hello")
Out[4]: [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o'] #先将字符串转换为列表,然后再相加,列表会改变
In [5]: a.__iadd__((1,2,3))
Out[5]: [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 1, 2, 3] #先将元组转换为列表,然后再相加,列表会改变
In [6]: a.__iadd__([1111,1113]) #列表相加,列表会改变
Out[6]: [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 1, 2, 3, 1111, 1113]
In [7]: a #a已改变
Out[7]: [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 1, 2, 3, 1111, 1113]
__imul__(self, value, /) Implement self*=value. self*=value value必须是integer类型
In [15]: a = [1,2,3,'abc']
In [16]: a.__imul__(2) #*2并返回给a
Out[16]: [1, 2, 3, 'abc', 1, 2, 3, 'abc']
In [17]: a #a已改变
Out[17]: [1, 2, 3, 'abc', 1, 2, 3, 'abc']
In [18]: a.__imul__([1,2]) #参数不是integer类型,报错
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-58ca78754a99> in <module>()
----> 1 a.__imul__([1,2])
TypeError: 'list' object cannot be interpreted as an integer
__init__(self, /, *args, **kwargs) Initialize self. See help(type(self)) for accurate signature. 列表初始化
In [23]: a = []
In [24]: b = [1,2,3,4]
In [25]: a.__init__(b)
In [26]: a
Out[26]: [1, 2, 3, 4]
In [27]: a.__init__((1,2,3)) #先将元组转换为列表,再初始化给a
In [28]: a
Out[28]: [1, 2, 3]
__iter__(self, /) Implement iter(self).
In [34]: a = [1,2,3,4,54]
In [35]: for i in a.__iter__():
...: print (i)
...:
1
2
3
4
54
In [36]: a.__iter__
Out[36]: <method-wrapper '__iter__' of list object at 0x024B7D00>
In [37]: a.__iter__() #列表类型的迭代器
Out[37]: <list_iterator at 0x25586b0>
__le__(self, value, /) Return self<=value. 判断列表是不大于某列表。与__eq__类似
__len__(self, /) Return len(self). 返回列表长度,即元素个数
In [38]: a = [1,2,3,"abc",(111,222,333)]
In [39]: a.__len__()
Out[39]: 5
In [40]: a.__len__
Out[40]: <method-wrapper '__len__' of list object at 0x024C44B8>
__lt__(self, value, /) Return self<value. 判断列表是小于某列表。与__eq__类似
__mul__(self, value, /) Return self*value.n 与__imul__类似,但本身不会改变
In [41]: a = [1,2,3,"abc",(111,222,333)]
In [42]: a.__mul__(2)
Out[42]: [1, 2, 3, 'abc', (111, 222, 333), 1, 2, 3, 'abc', (111, 222, 333)]
In [43]: a
Out[43]: [1, 2, 3, 'abc', (111, 222, 333)]
__ne__(self, value, /) Return self!=value.判断列表是不等于某列表。与__eq__类似
__new__(*args, **kwargs) from builtins.type
Create and return a new object. See help(type) for accurate signature. 创建一个新的列表对象。
In [1]: a = [1,2,3,4]
In [2]: b = a.__new__(list)
In [3]: b
Out[3]: []
In [4]: b = a.__new__(str)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-6fee1f0c3d80> in <module>()
----> 1 b = a.__new__(str)
TypeError: list.__new__(str): str is not a subtype of list
In [5]: b = a.__new__(tuple)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-18991a398a58> in <module>()
----> 1 b = a.__new__(tuple)
TypeError: list.__new__(tuple): tuple is not a subtype of list
__repr__(self, /) Return repr(self). 相当于repr函数
In [12]: a = [1,2,3,4]
In [13]: b = a.__repr__()
In [14]: b
Out[14]: '[1, 2, 3, 4]' #字符串
In [15]: a
Out[15]: [1, 2, 3, 4]
__reversed__(...) L.__reversed__() -- return a reverse iterator over the list 返回列表的逆序迭代器,列表本身不会改变
In [19]: a = [1,2,3,4]
In [20]: a.__reversed__()
Out[20]: <list_reverseiterator at 0x2538c50>
In [21]: a
Out[21]: [1, 2, 3, 4]
In [22]: b = a.__reversed__()
In [23]: for i in b:
...: print (i)
...:
4
3
2
1
__rmul__(self, value, /) Return self*value. 不知道与__mul__ 有啥区别。
In [34]: a = [1,2,3,4,"abc"]
In [35]: a.__mul__(-1)
Out[35]: []
In [36]: a.__mul__(0)
Out[36]: []
In [37]: a
Out[37]: [1, 2, 3, 4, 'abc']
In [38]: a.__mul__(2)
Out[38]: [1, 2, 3, 4, 'abc', 1, 2, 3, 4, 'abc']
__setitem__(self, key, value, /) Set self[key] to value. 改变列表某位置的对象。
In [39]: a
Out[39]: [1, 2, 3, 4, 'abc']
In [40]: a.__setitem__(2,"aaa")
In [41]: a
Out[41]: [1, 2, 'aaa', 4, 'abc']
In [43]: a
Out[43]: [1, 2, 3, 4, 'abc']
__sizeof__(...) L.__sizeof__() -- size of L in memory, in bytes 返回列表所占内存
In [44]: a = []
In [45]: a.__sizeof__
Out[45]: <function list.__sizeof__>
In [46]: a.__sizeof__()
Out[46]: 20
In [47]: a = [1]
In [48]: a.__sizeof__()
Out[48]: 24
In [49]: a = [1,2,3]
In [50]: a.__sizeof__()
Out[50]: 32
In [51]: a = ['a']
In [52]: a.__sizeof__()
Out[52]: 24
In [53]: a = ['abc']
In [54]: a.__sizeof__()
Out[54]: 24
append(...) L.append(object) -> None -- append object to end 添加对象到列表末尾
In [55]: a = [1]
In [56]: a.append(2)
In [57]: a
Out[57]: [1, 2]
In [58]: a.append('2')
In [59]: a
Out[59]: [1, 2, '2']
In [60]: a.append([1,2])
In [61]: a
Out[61]: [1, 2, '2', [1, 2]]
In [62]: a.append((3,4))
In [63]: a
Out[63]: [1, 2, '2', [1, 2], (3, 4)]
clear(...) L.clear() -> None -- remove all items from L 清空列表
In [64]: a
Out[64]: [1, 2, '2', [1, 2], (3, 4)]
In [65]: a.clear()
In [66]: a
Out[66]: []
copy(...) L.copy() -> list -- a shallow copy of L 列表浅拷贝
In [67]: a = [1,2,3,4]
In [68]: b = a.copy()
In [69]: a
Out[69]: [1, 2, 3, 4]
In [70]: b
Out[70]: [1, 2, 3, 4]
count(...) L.count(value) -> integer -- return number of occurrences of value 返回列表中某对象的个数。
In [71]: a = [1,2,3,'a','aa',[1,2]]
In [72]: a.count(1)
Out[72]: 1
In [73]: a.count('a')
Out[73]: 1
In [74]: a.count([1,2])
Out[74]: 1
In [75]: a.count(0)
Out[75]: 0
extend(...) L.extend(iterable) -> None -- extend list by appending elements from the iterable 将迭代器对象转换为列表并添加到列表末端。
In [80]: a = [1,2,3]
In [81]: a.extend((1,2,3))
In [82]: a
Out[82]: [1, 2, 3, 1, 2, 3]
In [83]: a.extend([4,5,6])
In [84]: a
Out[84]: [1, 2, 3, 1, 2, 3, 4, 5, 6]
index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
In [85]: a
Out[85]: [1, 2, 3, 1, 2, 3, 4, 5, 6]
In [86]: a.index(2)
Out[86]: 1 #返回第一个出现对象的位置
In [87]: a.index(7) #列表中不存在是时报错
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-87-e64802c95647> in <module>()
----> 1 a.index(7)
ValueError: 7 is not in list
insert(...)
| L.insert(index, object) -- insert object before index 在index位置插入任何对象
In [90]: a.insert(0,"abc")
In [91]: a
Out[91]: ['abc', 1, 2, 3, 1, 2, 3, 4, 5, 6]
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.
删除index位置处的对象并返回该对象,列表本身改变
In [92]: a.pop(2)
Out[92]: 2
In [93]: a
Out[93]: ['abc', 1, 3, 1, 2, 3, 4, 5, 6]
remove(...)
| L.remove(value) -> None -- remove first occurrence of value.
| Raises ValueError if the value is not present.
删除某个第一次出现的值,返回None
In [100]: a = [1,1,2,2,3,3,4,4,"aa",'aa']
In [101]: a.remove(1)
In [102]: a
Out[102]: [1, 2, 2, 3, 3, 4, 4, 'aa', 'aa']
In [103]: a.remove('aa')
In [104]: a
Out[104]: [1, 2, 2, 3, 3, 4, 4, 'aa']
reverse(...)
| L.reverse() -- reverse *IN PLACE* 列表逆序
In [105]: a = [1,2,3]
In [106]: a.reverse()
In [107]: a
Out[107]: [3, 2, 1]
sort(...) 对列表进行排序,列表元素必须是同一类型
| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
In [112]: a = [1,9,2,3,7,4]
In [113]: a.sort()
In [114]: a
Out[114]: [1, 2, 3, 4, 7, 9]