加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从一组(类似)字符串中确定前缀

发布时间:2020-12-20 10:35:13 所属栏目:Python 来源:网络整理
导读:我有一组字符串,例如 my_prefix_what_evermy_prefix_what_so_evermy_prefix_doesnt_matter 我只是想找到这些字符串中最长的公共部分,这里是前缀.在上面的结果应该是 my_prefix_ 字符串 my_prefix_what_evermy_prefix_what_so_evermy_doesnt_matter 应该导致
我有一组字符串,例如

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读