如何按索引从列表中删除元素?
我找到了list.remove(),但这会缓慢地按值扫描列表中的项。
如何按索引从列表中删除元素?
我找到了list.remove(),但这会缓慢地按值扫描列表中的项。
当前回答
通常,我使用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
其他回答
另一种通过索引从列表中删除元素的方法。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a[x:y]指向从索引x到y-1的元素。当我们将列表的该部分声明为空列表([])时,这些元素将被删除。
pop对于从列表中删除和保留项目也很有用。del实际上在哪里丢弃了物品。
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
通常,我使用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
这听起来不像你在处理一个列表,所以我会保持简短。您希望使用pop,因为它将删除元素而不是列表元素,因此应该使用del。要调用python中的最后一个元素,它是“-1”
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
您可以只搜索要删除的项目。这真的很简单。例子:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
输出:a c d e