检查其他列表中的字符串列表中是否存在字符串?

2024-06-16 11:18:14 发布

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

有没有比使用for循环更有效的方法来比较字符串列表?你知道吗

我想检查y中是否存在x字符串(在y字符串的任何部分)。你知道吗

x = ['a1' , 'a2', 'bk']
y = ['a1aa' , 'a2lop' , 'bnkl', 'a1sss', 'flask']
for i in x:
    print([i in str_y for str_y in y])

结果:

[True, False, False, True, False]
[False, True, False, False, False]
[False, False, False, False, False]

Tags: 方法字符串infalsetruea2列表for
3条回答

使用列表压缩:

In [4]: [[b in a for a in y] for b in x]
Out[4]:
[[True, False, False, True, False],
 [False, True, False, False, False],
 [False, False, False, False, False]]

测试时间:

 %timeit print([[b in a for a in y] for b in x])
<lots of printing>
228 µs ± 5.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
 %timeit for i in x:   print([i in x for x in y])
<lots of printing>
492 µs ± 4.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

所以有一半的时间。你知道吗

你可以只用list comprehension。你知道吗

x = ['a1' , 'a2', 'bk']
y = ['a1aa' , 'a2lop' , 'bnkl', 'a1sss', 'flask']
print([[xi in z for z in y] for xi in x])

您可以使用itertools.product在一个列表中获取所有结果:

In [61]: x = ['a1' , 'a2', 'bk']
    ...: y = ['a1aa' , 'a2lop' , 'bnkl', 'a1sss', 'flask']
    ...: 

In [62]: [i in j for i, j in product(x, y)]

或者作为一种函数方法,您可以同时使用starmapproduct

from itertools import product, starmap
from operator import contains

list((starmap(contains, product(y, x))))

另外,矢量化但不是很优化的方法如下:

In [139]: (np.core.defchararray.find(y[:,None], x) != -1).T
Out[139]: 
array([[ True, False, False,  True, False],
       [False,  True, False, False, False],
       [False, False, False, False, False]])

相关问题 更多 >