gpt4 book ai didi

python - 从一组(相似的)字符串中确定前缀

转载 作者:IT老高 更新时间:2023-10-28 21:43:13 26 4
gpt4 key购买 nike

我有一组字符串,例如

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

我只是想找到这些字符串中最长的公共(public)部分,这里是前缀。在上面的结果应该是

my_prefix_

字符串

my_prefix_what_ever
my_prefix_what_so_ever
my_doesnt_matter

应该是前缀

my_

在 Python 中是否有一种相对轻松的方式来确定前缀(无需手动迭代每个字符)?

PS:我使用的是 Python 2.6.3。

最佳答案

永远不要重写提供给您的内容:os.path.commonprefix正是这样做的:

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.

为了与其他答案进行比较,代码如下:

# 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

关于python - 从一组(相似的)字符串中确定前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6718196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com