List comprehension and intersection problem [duplicate]

a 夏天 提交于 2019-12-24 06:52:21

问题


list(set(a[0]) & set(a[1]) & set(a[2]) & set(a[3]) & set(a[4]))

Does anyone know how to write this in a way such that we dont need to know apriori how many lists we will be given? (ie 5 not hard coded in)?

Each a is a list of varying size.


回答1:


As long as you have at least one set, you can do this:

list(set(a[0]).intersection(*a[1:]))

If there might be no sets, you have to decide for yourself what the "intersection of no sets" actually should mean in your application. If you want the empty set:

list(set(*a[:1]).intersection(*a[1:]))



回答2:


I think it's worth noting, at least to improve one's general programming understanding, that what you want to do can be described as mapping and then reducing or folding. Specifically, you want to map set over a and then fold & over the result.

I'm not a Python expert, but it can be done like this in Python:

from functools import reduce

a = [
    [1,2,3],
    [1,2,3,4],
    [1,2,4,5],
    [1,2,3,5],
]

intersection = lambda x, y: x & y

mapped = list(map(set, a))

reduced = reduce(intersection, mapped)

Note that this implementation requires a to be non-empty.



来源:https://stackoverflow.com/questions/59275902/list-comprehension-and-intersection-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!