给定一个字符串列表,确定一个字符串是否是另一个字符串的前缀

2024-09-25 04:30:49 发布

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

我想写一个Python函数来检查一个字符串是否是另一个字符串的前缀字符串;而不是另一个字符串的任意子字符串;必须是prefix。如果是,则返回True。例如

list = ['abc', 'abcd', 'xyx', 'mno']

返回True,因为'abc''abcd'的前缀。在

^{pr2}$

返回False

我尝试了startwith()和列表理解,但效果不太理想。 感谢您的帮助和建议。在


Tags: 函数字符串falsetrue列表prefixlistabc
3条回答

使用itertools

import itertools

list1 = ["abc", "xyz", "abc123"]
products = itertools.product(list1, list1)
is_substringy = any(x.startswith(y) for x, y in products if x != y)

这不是很优化,但是根据你要处理的数据量,代码相当优雅(而且很短);在你的用例中,这可能胜过速度。在

但是,这假设您在列表中没有纯重复(但是您的示例中没有)。在

让我们首先对给定的lstw.r.t长度进行排序,因为已知的事实是子字符串的长度总是小于或等于原始字符串,因此在排序之后,我们在列表的开头有较小长度的字符串,然后在排序后的列表中迭代,比较当前元素与旁边的所有元素它,这个小的优化可以降低问题的复杂性,因为现在我们不必将每个元素与其他元素进行比较。在

lst1 = ['abc', 'abcd', 'xyx', 'mno']
lst2 = ['abc', 'xyzabc', 'mno']
lst3 = ["abc", "abc"]

def check_list(lst):
    lst = list(set(lst))    #if you want to avoid redundant strings.
    lst.sort(key = lambda x:len(x))

    n = len(lst)
    for i in xrange(n):
        for j in xrange(i+1, n):
            if lst[j].startswith(lst[i]):
                return True
    return False

print check_list(lst1)
print check_list(lst2)
print check_list(lst3)
>>> True
>>> False
>>> False #incase you use lst = list(set(lst))
import itertools
mlist = ['abc', 'abcd', 'xyx', 'mno']
#combination of list elements, 2-by-2. without repetition  
In [638]: for i,j in itertools.combinations(mlist,2):
    print (i,j)
   .....:     
('abc', 'abcd')
('abc', 'xyx')
('abc', 'mno')
('abcd', 'xyx')
('abcd', 'mno')
('xyx', 'mno')
#r holds the final result. if there is any pair where one is a prefixed of another 
r=False
In [639]: for i,j in itertools.combinations(mlist,2):  
    r = r or i.startswith(j) # if i is the prefix of j. logical or
    r = r or j.startswith(i) # if j is the prefix of i
   .....:     

In [640]: r
Out[640]: True

相关问题 更多 >