list 常见操作
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
- append()将元素添加到列表末尾,而不影响列表中其他所有元素
>>> test=[1,2,3,4]
>>> test.append(33)
>>> test
[1, 2, 3, 4, 33]
>>> test=[1,2,3,4]
>>> test.append(1)
>>> test.count(1)
2
- extend()用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
>>> test=[1,'wang','hao','ran',23]
>>> t_add=[1818,'hahaha']
>>> test.extend(t_add)
>>> test
[1, 'wang', 'hao', 'ran', 23, 1818, 'hahaha']
- index从列表中找出某个值第一个匹配项的索引位置。
>>> test.index('wang')
1
>>> test=[1,2,3,'wang']
>>> test.insert(0,'hao')
>>> test
['hao', 1, 2, 3, 'wang']
- pop()可以用来删除列表中任何位置的元素,但实际是将某个位置的元素弹出去,类似于C栈中的pop。
- 若pop()内未指定任何位置则默认pop操作列表最后一个
>>> test
['hao', 1, 2, 3, 'wang']
>>> test.pop(0)
'hao'
>>> test
[1, 2, 3, 'wang']
- remove()不必知道元素所在位置,可直接删除所知道的元素值
>>> test
[1, 2, 3, 'wang']
>>> test.remove(2)
>>> test
[1, 3, 'wang']
>>> test
[1, 3, 'wang']
>>> test.reverse()
>>> test
['wang', 3, 1]
>>> test=[9,6,3,1]
>>> test.sort()
>>> test
[1, 3, 6, 9]
>>> test=[9,6,3,1]
>>> sorted(test)
[1, 3, 6, 9]
>>> test
[9, 6, 3, 1]
>>> len(test)
4