我想写一些从数组中移除特定元素的代码。我知道我必须对数组进行for循环才能找到与内容匹配的元素。
假设我有一个电子邮件数组,我想去掉与某个电子邮件字符串匹配的元素。
我实际上喜欢使用for循环结构,因为我也需要对其他数组使用相同的索引。
下面是我的代码:
for index, item in emails:
if emails[index] == 'something@something.com':
emails.pop(index)
otherarray.pop(index)发布于 2011-08-19 16:30:03
最明智的方法是使用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(),它们给出的是列表,而不是数组。不是一回事。
https://stackoverflow.com/questions/7118276
复制相似问题