jah*_*max 338 python arrays string exists
如何检查数组中的任何字符串是否存在于另一个字符串中?
喜欢:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
Run Code Online (Sandbox Code Playgroud)
该代码不起作用,只是为了展示我想要实现的目标.
Mar*_*ers 636
你可以使用any:
if any(x in str for x in a):
Run Code Online (Sandbox Code Playgroud)
类似于检查是否找到列表中的所有字符串,请使用all而不是any.
zon*_*ndo 57
any()如果你想要的只是True或者False,那么到目前为止是最好的方法,但是如果你想知道哪些字符串/字符串匹配,你可以使用一些东西.
如果您想要第一个匹配(False默认情况下):
match = next((x for x in a if x in str), False)
Run Code Online (Sandbox Code Playgroud)
如果你想得到所有的比赛(包括重复):
matches = [x for x in a if x in str]
Run Code Online (Sandbox Code Playgroud)
如果您想获得所有非重复匹配(忽略订单):
matches = {x for x in a if x in str}
Run Code Online (Sandbox Code Playgroud)
如果您想以正确的顺序获得所有非重复匹配:
matches = []
for x in a:
if x in str and x not in matches:
matches.append(x)
Run Code Online (Sandbox Code Playgroud)
jbe*_*das 41
如果字符串在a或str变长,你应该小心.直接的解决方案采用O(S*(A ^ 2)),其中S长度为strA,A是所有字符串长度的总和a.要获得更快的解决方案,请查看用于字符串匹配的Aho-Corasick算法,该算法以线性时间O(S + A)运行.
jet*_*com 19
只是为了增加一些多样性regex:
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
print 'possible matches thanks to regex'
else:
print 'no matches'
Run Code Online (Sandbox Code Playgroud)
或者如果你的名单太长 - any(re.findall(r'|'.join(a), str, re.IGNORECASE))
Ber*_*pac 11
一个令人惊讶的快速方法是使用set:
a = ['a', 'b', 'c']
str = "a123"
if set(a) & set(str):
print("some of the strings found in str")
else:
print("no strings found in str")
Run Code Online (Sandbox Code Playgroud)
这适用于如果a不包含任何多字符的值(在这种情况下,使用any所列出以上)。如果是这样,指定a为字符串更简单:a = 'abc'。
你需要迭代a的元素.
a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:
if item in str:
found_a_string = True
if found_a_string:
print "found a match"
else:
print "no match found"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
278041 次 |
| 最近记录: |