use*_*190 39 python arrays object
在Python中,如何从对象数组中删除对象?像这样:
x = object()
y = object()
array = [x,y]
# Remove x
Run Code Online (Sandbox Code Playgroud)
我已经尝试array.remove()
但它只适用于值,而不是数组中的特定位置.我需要能够通过寻址它的位置来删除对象(remove array[0]
)
Ric*_*llo 77
在python中没有数组,而是使用列表.有多种方法可以从列表中删除对象:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
Run Code Online (Sandbox Code Playgroud)
在你的情况下,使用适当的方法是pop,因为它需要删除索引:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
Run Code Online (Sandbox Code Playgroud)
您可以尝试从数组中动态删除对象而不循环遍历它吗?其中 e 和 t 只是随机对象。
>>> e = {'b':1, 'w': 2}
>>> t = {'b':1, 'w': 3}
>>> p = [e,t]
>>> p
[{'b': 1, 'w': 2}, {'b': 1, 'w': 3}]
>>>
>>> p.pop(p.index({'b':1, 'w': 3}))
{'b': 1, 'w': 3}
>>> p
[{'b': 1, 'w': 2}]
>>>
Run Code Online (Sandbox Code Playgroud)
如果要从列表中删除多个对象。有多种方法可以从列表中删除对象
试试这个代码。a是具有所有对象的列表,b是要删除的列表对象。
例如:
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
Run Code Online (Sandbox Code Playgroud)
[1,4,5,6]
我的输出是希望,它将为您工作
归档时间: |
|
查看次数: |
187106 次 |
最近记录: |