Determine prefix from a set of (similar) strings

前端 未结 9 2105
我在风中等你
我在风中等你 2020-11-27 14:25

I have a set of strings, e.g.

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

I simply want to find the longest common p

9条回答
  •  一整个雨季
    2020-11-27 14:53

    The second line of this employs the reduce function on each character in the input strings. It returns a list of N+1 elements where N is length of the shortest input string.

    Each element in lot is either (a) the input character, if all input strings match at that position, or (b) None. lot.index(None) is the position of the first None in lot: the length of the common prefix. out is that common prefix.

    val = ["axc", "abc", "abc"]
    lot = [reduce(lambda a, b: a if a == b else None, x) for x in zip(*val)] + [None]
    out = val[0][:lot.index(None)]
    

提交回复
热议问题