从一组(相似的)字符串中确定前缀 [英] Determine prefix from a set of (similar) strings
问题描述
我有一组字符串,例如
my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter
我只想找到这些字符串的最长公共部分,这里是前缀.上面的结果应该是
I simply want to find the longest common portion of these strings, here the prefix. In the above the result should be
my_prefix_
字符串
my_prefix_what_ever
my_prefix_what_so_ever
my_doesnt_matter
应该导致前缀
my_
在 Python 中是否有一种相对轻松的方法来确定前缀(无需手动遍历每个字符)?
Is there a relatively painless way in Python to determine the prefix (without having to iterate over each character manually)?
PS:我使用的是 Python 2.6.3.
PS: I'm using Python 2.6.3.
推荐答案
永远不要重写提供给您的内容:os.path.commonprefix
正是这样做的:
Never rewrite what is provided to you: os.path.commonprefix
does exactly this:
返回最长路径前缀(取逐个字符),它是列表中所有路径的前缀.如果列出为空,返回空字符串 (''
).请注意,这可能会返回无效路径,因为它一次处理一个字符.
Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (
''
). Note that this may return invalid paths because it works a character at a time.
为了与其他答案进行比较,代码如下:
For comparison to the other answers, here's the code:
# Return the longest prefix of all list elements.
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
这篇关于从一组(相似的)字符串中确定前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!