如何在python数组中查找字符串的一部分

2024-04-29 16:09:35 发布

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

我有一个数组,有一列数字和一列字符串。我需要找到包含字符串某一部分的索引。示例:

array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

我在入门编程,所以我的导师告诉我在数组[index]中使用if'stringpart'来获得一个布尔数组,用于解决问题。我认为应该发生什么:

input:
'red' in array[:,1]
output:
(true,false,true,false)

事实上,我完全错了。我在函数之外测试了代码,并将其应用到只包含字符串的数组中,结果仍然是false。但我用一支完整的“红色蜡笔”试了一下,结果是真的。这个部分字符串代码适用于教师和其他学生。为什么不适合我?你知道吗


Tags: 字符串代码falsetrue示例数字greenred
3条回答

对于矢量化解决方案,可以使用np.char模块:

a = np.array([['4', 'red crayon'],
              ['2', 'purple people eater'],
              ['6', 'red hammer'],
              ['12', 'green screwdriver']])
np.char.find(a[:, 1], 'red') > -1
# array([ True, False,  True, False], dtype=bool)

您需要检查子字符串是否存在于数组的任何元素中:

a = [['4', 'red crayon'],
     ['2', 'purple people eater'],
     ['6', 'red hammer'],
     ['12', 'green screwdriver']]

[True if any(['red' in elt for elt in sub]) else False for sub in a]

输出:

[True, False, True, False]

You can do without for loop:

import numpy as np
wow=np.array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

your_word='red'
print(list(map(lambda x:True if your_word in x[1].split() else False ,wow)))

输出:

[True, False, True, False]

相关问题 更多 >