Determine prefix from a set of (similar) strings

前端 未结 9 2106
我在风中等你
我在风中等你 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 15:17

    Ned Batchelder is probably right. But for the fun of it, here's a more efficient version of phimuemue's answer using itertools.

    import itertools
    
    strings = ['my_prefix_what_ever', 
               'my_prefix_what_so_ever', 
               'my_prefix_doesnt_matter']
    
    def all_same(x):
        return all(x[0] == y for y in x)
    
    char_tuples = itertools.izip(*strings)
    prefix_tuples = itertools.takewhile(all_same, char_tuples)
    ''.join(x[0] for x in prefix_tuples)
    

    As an affront to readability, here's a one-line version :)

    >>> from itertools import takewhile, izip
    >>> ''.join(c[0] for c in takewhile(lambda x: all(x[0] == y for y in x), izip(*strings)))
    'my_prefix_'
    

提交回复
热议问题