如何使用掩码从数组中删除值?

2024-05-19 01:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

主题。例如:

array = ['value1', 'value2', 'value3', 'value4', ...(here is many values like value5, value6, value7, value49 etc.)..., 'value50' 'something', 'something2']

我应该从这个数组中删除value*。我该怎么做?你知道吗


Tags: 主题hereisarraymanylikevaluesvalue1
2条回答

使用列表理解,筛选出以value开头的值:

>>> array = ['value1', 'value2', 'value3', 'value4', 'value50', 'something', 'something2']
>>> array = [x for x in array if not x.startswith('value')]  # NOTE: used `not`
>>> array
['something', 'something2']

把简单的事情复杂化是我的代码:)

from itertools import ifilterfalse
ifilterfalse(lambda x:x.startswith('value'),array)

注意,如果列表中有整数值,您将得到 AttributeError:'int'对象没有属性'startswith'

因此,要处理列表“array”中的整数,我们将使用以下简单循环:

res = []
for ele in array:
if type(ele) is int:
    res.append(ele)
elif not ele.startswith('value'):
    res.append(ele)

相关问题 更多 >

    热门问题