开发者

returning matches from an unknown number of python lists

I have a list which contains 1-5 lists within it. I want to return only the values which appear in all the lists. I can easily create an exception for it there is only one list, but I can't think of a way round it when there are an multiple (un开发者_开发问答known number of) lists. For example:

[[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]

would only return 2, because it's the only list item to appear in all the sub-lists

How can I achieve this?


reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]))


You can use frozenset.intersection (or set.intersection if you prefer):

>>> l = [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]
>>> frozenset.intersection(*(frozenset(x) for x in l))
frozenset({2})

Add a call to list if you want the result as a list instead of a set.


I suggest this solution:

s = [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]

#flatten the list
flat = sum(s,[])

#only keep digits that appear a certain number of times (size of s)
filtered = filter(lambda x: flat.count(x) == len(s),flat)

# clear repeated values
list(set(filtered))

There are better ways to do this but this one is more explicit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜