Take the intersection of an arbitrary number of lists in python

前端 未结 7 1912
失恋的感觉
失恋的感觉 2020-12-21 05:37

Suppose I have a list of lists of elements which are all the same (i\'ll use ints in this example)

[range(100)[::4], range(100)[::3], range(100)         


        
7条回答
  •  [愿得一人]
    2020-12-21 06:31

    You can treat them as sets and use set.intersection():

    lists = [range(100)[::4], range(100)[::3], range(100)[::2], range(100)[::1]]
    sets = [set(l) for l in lists]
    
    isect = reduce(lambda x,y: x.intersection(y), sets)
    

提交回复
热议问题