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)
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
使用
itertools
这不是很优化,但是根据你要处理的数据量,代码相当优雅(而且很短);在你的用例中,这可能胜过速度。在
但是,这假设您在列表中没有纯重复(但是您的示例中没有)。在
让我们首先对给定的
lst
w.r.t长度进行排序,因为已知的事实是子字符串的长度总是小于或等于原始字符串,因此在排序之后,我们在列表的开头有较小长度的字符串,然后在排序后的列表中迭代,比较当前元素与旁边的所有元素它,这个小的优化可以降低问题的复杂性,因为现在我们不必将每个元素与其他元素进行比较。在相关问题 更多 >
编程相关推荐