获取列表中所有单词的最长公共字符串前缀

时间:2016-10-28 18:41:22

标签: python stemming

是否有一个函数返回列表中所有值开头的最长字符串(长度):

["flexible","flexile","flexion","flexor"]

应该返回:"flex"或4

为此:["flexible","flexile","flexion","flexor","ape"],它应该返回一个空字符串或0;

2 个答案:

答案 0 :(得分:15)

>>> import os
>>> os.path.commonprefix(["flexible","flexile","flexion","flexor"])
'flex'

答案 1 :(得分:0)

这适用于任何迭代:

from itertools import takewhile

def commonprefix(xs):
  return map(lambda xs: xs[0],takewhile(lambda xs: len(set(xs)) == 1,zip(*xs)))

print len(commonprefix(["flexible","flexile","flexion","flexor"])) # 4
print len(commonprefix(["flexible","flexile","flexion","flexor","ape"])) # 0