3 回答
TA贡献1843条经验 获得超7个赞
pop
:
a = ['a', 'b', 'c', 'd']a.pop(1)# now a is ['a', 'c', 'd']
pop
a = ['a', 'b', 'c', 'd']a.pop()# now a is ['a', 'b', 'c']
TA贡献1942条经验 获得超3个赞
使用切片(这并不能从原始列表中删除项目):
__getitem__
):
>>> a = [1, 2, 3, 4, 5, 6]>>> index = 3 # Only positive index>>> a = a[:index] + a[index+1 :]# a is now [1, 2, 3, 5, 6]
注:pop
del
a[:index]
a[index+1:]
a
__getitem__
__add__
class foo(object): def __init__(self, items): self.items = items def __getitem__(self, index): return foo(self.items[index]) def __add__(self, right): return foo( self.items + right.items )
list
__getitem__
__add__
三种方法在效率方面的比较:
a = range(10)index = 3
del object[index]
__del__
def del_method(): global a global index del a[index]
10 0 LOAD_GLOBAL 0 (a) 3 LOAD_GLOBAL 1 (index) 6 DELETE_SUBSCR # This is the line that deletes the item 7 LOAD_CONST 0 (None) 10 RETURN_VALUENone
pop
def pop_method(): global a global index a.pop(index)
17 0 LOAD_GLOBAL 0 (a) 3 LOAD_ATTR 1 (pop) 6 LOAD_GLOBAL 2 (index) 9 CALL_FUNCTION 1 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE
切片和添加方法。
def slice_method(): global a global index a = a[:index] + a[index+1:]
24 0 LOAD_GLOBAL 0 (a) 3 LOAD_GLOBAL 1 (index) 6 SLICE+2 7 LOAD_GLOBAL 0 (a) 10 LOAD_GLOBAL 1 (index) 13 LOAD_CONST 1 (1) 16 BINARY_ADD 17 SLICE+1 18 BINARY_ADD 19 STORE_GLOBAL 0 (a) 22 LOAD_CONST 0 (None) 25 RETURN_VALUENone
return None
a
index
.
添加回答
举报