返回python中列表中单词(开头)常用的前导字符串

时间:2014-10-15 19:43:37

标签: python

我有这样的经历之一,我写的东西应该是微不足道的,它需要比预期更多的代码行。有人可以提出一个更优雅的解决方案来解决(从单词列表中)拉出所有共同的主要字符串的问题吗?我已经包含了我的代码,所以你可以嘲笑它。

def _allStartWith( words ):
     """ Return leading string common to (the start of) words in a list  """

     n = len( words[0] )
     for other in words[1:]:
         if other != words[0]:
            n = min( n, _sameFor( other, words[0] ) )
     return words[0][:n]   

,其中

def _sameFor( word1, word2 ):
            """ How many letters are the same before one is false ?"""
            return ( [ c1==c2 for c1, c2 in zip( word1, word2 ) ] + [ False ] ).index( False )

例如,

 _allStartWith( [ 'foo2you and you','foo bar and you'] )
    'foo'

1 个答案:

答案 0 :(得分:1)

您可以滥用os.path.commonprefix()

>>> import os
>>> os.path.commonprefix(['foo2you and you', 'foo bar and you'])
'foo'

这是its 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