如何使用 python 从数组中删除特定元素

我想写一些从数组中删除特定元素的代码。我知道我必须通过 for循环数组来找到匹配内容的元素。

假设我有一个电子邮件数组,我想去掉与某个电子邮件字符串匹配的元素。

我实际上希望使用 for 循环结构,因为我还需要对其他数组使用相同的索引。

下面是我的代码:

for index, item in emails:
if emails[index] == 'something@something.com':
emails.pop(index)
otherarray.pop(index)
547700 次浏览

您不需要迭代数组,只需:

>>> x = ['ala@ala.com', 'bala@bala.com']
>>> x
['ala@ala.com', 'bala@bala.com']
>>> x.remove('ala@ala.com')
>>> x
['bala@bala.com']

这将删除与字符串匹配的第一个匹配项。

编辑: 在编辑之后,你仍然不需要重复。只需要:

index = initial_list.index(item1)
del initial_list[index]
del other_list[index]

理智的做法是使用 zip()和列表内涵/生成器表达式:

filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == 'something@something.com')


new_emails, new_other_list = zip(*filtered)

此外,如果您没有使用 array.array()numpy.array(),那么很可能您使用的是 []list(),它们给您列表,而不是数组。这不一样。

如果您需要 for 循环中的索引,那么 for 循环不正确,请使用:

for index, item in enumerate(emails):
# whatever (but you can't remove element while iterating)

在您的例子中,Bogdan 解决方案是可以的,但是您的数据结构选择不是很好。必须使用来自一个列表的数据和来自同一索引中的另一个列表的数据来维护这两个列表是很麻烦的。

元组列表(电子邮件,其他数据)可能更好,或以电子邮件为关键字的 dict。

使用 filter()lambda可以提供一种简洁的方法去除不需要的值:

newEmails = list(filter(lambda x : x != 'something@something.com', emails))

这不会修改电子邮件。它创建新列表 newEmail,其中只包含匿名函数返回 True 的元素。

对于这个问题还有另一种解决方案,它也处理重复匹配。

我们从两个等长的列表开始: emailsotherarray。目标是从 emails[i] == 'something@something.com'所在的每个索引 i的两个列表中删除项。

这可以通过使用列表内涵,然后通过 zip进行分裂来实现:

emails = ['abc@def.com', 'something@something.com', 'ghi@jkl.com']
otherarray = ['some', 'other', 'details']


from operator import itemgetter


res = [(i, j) for i, j in zip(emails, otherarray) if i!= 'something@something.com']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))


print(emails)      # ['abc@def.com', 'ghi@jkl.com']
print(otherarray)  # ['some', 'details']

如果要删除数组的索引:

使用 array _ name. pop (index _ no.)

例如:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

如果您想从数组中删除特定的字符串/元素,那么

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']