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

后端 未结 6 707
温柔的废话
温柔的废话 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 08:07

    An modernized Vertical scan solution using a generator expression and Python 3's builtin zip:

    lst = [[3,2,1], [3,2,1,1,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]
    
    next(zip(*(x for x in zip(*lst) if len(set(x)) == 1)))
    # (3, 2, 1)
    

    See also a related Leetcode problem - Longest Common Prefix.

提交回复
热议问题