I have a list of lists where the length of the lists are same. I need to find the common elements from them with the order of occurrence maintained. For example:
Suppose the list of lists is
The output list should contain
['a','e','c'] Priority should be given to elements which occur earlier in most of the lists. In this example ‘a’ occurs earlier, then ‘e’ and so on.
How to proceed with this?
you could find common items first then sorted it
from collections import defaultdict data = [['a','e','d','c','f'],['e','g','a','d','c'],['c','a','h','e','j']] common = set(data) for line in data: common = common.intersection(set(line)) res = defaultdict(int) for line in data: for idx, item in enumerate(line): if item in common: res[item] += idx [item for item in sorted(res.items(), key=lambda x: x)]
['a', 'e', 'c']