Python:列表中的完整字符串与部分字符串的交集 [英] Python: Intersection of full string from list with partial string
本文介绍了Python:列表中的完整字符串与部分字符串的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个字符串和一个字符串列表:
Let's say I have a string and a list of strings:
a = 'ABCDEFG'
b = ['ABC', 'QRS', 'AHQ']
我如何拔出列表b中与字符串a的一部分完全匹配的字符串?因此,返回值将类似于['ABC']
How can I pull out the string in list b that matches up perfectly with a section of the string a? So the would return would be something like ['ABC']
最重要的问题是我有数千万个字符串,因此时间效率至关重要.
The most important issue is that I have tens of millions of strings, so that time efficiency is essential.
推荐答案
如果只希望b中的第一个匹配项:
If you only want the first match in b:
next((s for s in b if s in a), None)
这样做的好处是,一旦找到匹配项,就会将其短路,而其他列表解决方案将继续保持下去.如果找不到匹配项,它将返回None
.
This has the advantage of short-circuiting as soon as it finds a match whereas the other list solutions will keep going. If no match is found, it will return None
.
这篇关于Python:列表中的完整字符串与部分字符串的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文