What is the Pythonic way to find the longest common prefix of a list of lists?

后端 未结 6 700
温柔的废话
温柔的废话 2020-12-03 07:27

Given: a list of lists, such as [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]

Todo: Find the longest common

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 07:56

    I am not sure how pythonic it is

    from itertools import takewhile,izip
    
    x = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]
    
    def allsame(x):
        return len(set(x)) == 1
    
    r = [i[0] for i in takewhile(allsame ,izip(*x))]
    

提交回复
热议问题