我想要一个 python 函数,给定列表
mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn']
返回字符串“abc”,即列表中所有元素包含的最长的一段。我有一个解决方案,只需循环遍历 mystring[0] 的切片,并将其与其余部分进行比较,并在找到第一个不匹配的子字符串时跳出循环。然而,我怀疑一定有一种更高效、更优雅、更Python 的方式来做到这一点。
有人可以指出如何正确执行此操作吗?
I would like to have a python function that given the list
mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn']
returns the string 'abc', i.e., the longest piece contained by all the elements in the list. I have a solution which just loops through the slices of mystring[0]
, and compares it to the rest, and breaks out of the loop, whenever the first unmatching substring is found. However, I suspect that there must be a more efficient, elegant, and pythonic way of doing this.
Could someone point out how to do this properly?
发布评论
评论(2)
按照您描述的方式,您希望在起点处使用最大的子字符串:
The way you described, you want the biggest substring at the starting point:
一旦您意识到“最长公共子串”是您所描述的问题,就很容易找到您想要的内容:
例如,来自 维基教科书:
Once you realize that "Longest Common Substring" is the problem you're describing, it's easy to find what you want:
eg, from Wikibooks: