如何使用python从数组中删除特定元素 [英] How to remove specific element from an array using python

查看:40
本文介绍了如何使用python从数组中删除特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一些从数组中删除特定元素的东西.我知道我必须 for 循环遍历数组才能找到与内容匹配的元素.

假设我有一组电子邮件,我想删除与某个电子邮件字符串匹配的元素.

我实际上想使用 for 循环结构,因为我也需要对其他数组使用相同的索引.

这是我拥有的代码:

 用于索引,电子邮件中的项目:如果电子邮件[索引] == 'something@something.com':emails.pop(索引)otherarray.pop(索引)

解决方案

您不需要迭代数组.只是:

<预><代码>>>>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[索引]del other_list[索引]

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.

I'd actually like to use the for loop structure because I need to use the same index for other arrays as well.

Here is the code that I have:

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.

EDIT: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆