Numpy:获取数组的元素,该元素在比较中包含True

2024-03-29 14:17:46 发布

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

import numpy as np  
import re

list1= ['651ac1', '21581', '13737|14047', '22262', '12281', '12226', '61415', '61495']
regexp = '[a-zA-Z]'
selection = np.array([bool(re.search(regexp, element)) for element in list1])
if True in selection:
    #get_element_containing_true

selection如下所示:

selection
array([ True, False, False, False, False, False, False, False, False], dtype=bool)

我想得到数组中包含True的元素。我怎么得到这个?你知道吗


Tags: inimportrenumpyfalsetrueasnp
2条回答

你真的需要这里的numpy(如果不需要,请参阅@Divakar's answer)?如果这样做,可以将list1转换为np.array并索引:

np.array(list1)[selection]

这被称为^{}。以防你感兴趣。你知道吗


性能提示:如果您多次使用正则表达式:编译它并重用已编译的表达式:

regexp = re.compile('[a-zA-Z]')
selection = np.array([bool(regexp.search(element)) for element in list1])

这可以更快更容易地与另一个答案结合起来。你知道吗

你可以直接在list-comprehension-

[element for element in list1 if bool(re.search(regexp, element))]

仔细观察,使用搜索方法,我们得到一个匹配的对象:

In [175]: re.search(regexp, list1[0])
Out[175]: <_sre.SRE_Match at 0x7fc30bac1c60>

对于不匹配的情况,我们得到None。你知道吗

根据^{}

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a bool() method.

因此,如果搜索方法的结果直接反馈给IF,我们得到匹配的对象,None没有匹配的对象。因此,使用定义,对于IF,匹配将被评估为True,否则将被评估为False。因此,我们可以跳过那里的bool(),得到一个简化的版本,就像这样-

[element for element in list1 if re.search(regexp, element)]

相关问题 更多 >