如何使用python从数组中删除特定元素 [英] How to remove specific element from an array using python
问题描述
我想写一些东西从数组中删除一个特定的元素.我知道我必须for
遍历数组以查找与内容匹配的元素.
I want to write something that removes a specific element from an array. I know that I have to for
loop through the array to find the element that matches the content.
假设我有一系列电子邮件,并且想摆脱与某些电子邮件字符串匹配的元素.
Let's say that I have an array of emails and I want to get rid of the element that matches some email string.
我实际上想使用for循环结构,因为我还需要对其他数组使用相同的索引.
I'd actually like to use the for loop structure because I need to use the same index for other arrays as well.
这是我拥有的代码:
for index, item in emails:
if emails[index] == 'something@something.com':
emails.pop(index)
otherarray.pop(index)
推荐答案
您不需要迭代数组.只是:
You don't need to iterate the array. Just:
>>> x = ['ala@ala.com', 'bala@bala.com']
>>> x
['ala@ala.com', 'bala@bala.com']
>>> x.remove('ala@ala.com')
>>> x
['bala@bala.com']
这将删除与字符串匹配的第一个匹配项.
This will remove the first occurence that matches the string.
编辑后,您仍然不需要迭代.只要做:
After your edit, you still don't need to iterate over. Just do:
index = initial_list.index(item1)
del initial_list[index]
del other_list[index]
这篇关于如何使用python从数组中删除特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!