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

后端 未结 6 701
温柔的废话
温柔的废话 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:19

    Given your example code, you seem to want a version of reduce(set.intersection, map(set, l)) that preserves the initial order of the first list.

    This requires algorithmic improvements, not stylistic improvements; "pythonic" code alone won't do you any good here. Think about the situation that must hold for all values that occur in every list:

    Given a list of lists, a value occurs in every list if and only if it occurs in nlist lists, where nlist is the total number of lists.

    If we can guarantee that each value occurs only once in every list, then the above can be rephrased:

    Given a list of lists of unique items, a value occurs in every list if and only if it occurs nlist times total.

    We can use sets to guarantee that the items in our lists are unique, so we can combine this latter principle with a simple counting strategy:

    >>> l = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]
    >>> count = {}
    >>> for i in itertools.chain.from_iterable(map(set, l)):
    ...     count[i] = count.get(i, 0) + 1
    ...     
    

    Now all we have to do is filter the original list:

    >>> [i for i in l[0] if count[i] == len(l)]
    [3, 2, 1]
    

提交回复
热议问题