利用在python列表任意数量的交叉点交叉点、数量、列表、python

2023-09-11 23:26:19 作者:猪尛萌

假设我有元素这是列表的列表都一样(我将使用 INT S在这个例子中)

  [范围(100):: 4],范围(100):: 3],范围(100)[:: 2],范围(100):: 1]
 

什么将是一个很好的和/或有效率的方式,采取这些列表的交集(所以你会得到的是每个列表中的每个元素)? 对于这个例子,这将是:

  [0,12,24,36,48,60,72,84,96]
 

解决方案 万能Python的秘诀 操纵数据的内置工具

使用套,其中有交集的方法。

 >>> S =集()
>>> s.add(4)
>>> s.add(5)
>>>小号
集([4,5])
>>>吨=集([2,4,9])
>>> s.intersection(T)
集([4])
 

有关你的榜样,像

 >>>数据= [范围(100)[:: 4],范围(100)[:: 3],范围(100)[:: 2],范围(100)[:: 1]
>>>套=地图(集,数据)
>>>打印set.intersection(*套)
集([0,96,36,72,12,48,84,24,60])
 

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)[::2], range(100)[::1]]

What would be a nice and/or efficient way to take the intersection of these lists (so you would get every element that is in each of the lists)? For the example that would be:

[0, 12, 24, 36, 48, 60, 72, 84, 96]

解决方案

Use sets, which have an intersection method.

>>> s = set()
>>> s.add(4)
>>> s.add(5)
>>> s
set([4, 5])
>>> t = set([2, 4, 9])
>>> s.intersection(t)
set([4])

For your example, something like

>>> data = [range(100)[::4], range(100)[::3], range(100)[::2], range(100)[::1]]
>>> sets = map(set, data)
>>> print set.intersection(*sets)
set([0, 96, 36, 72, 12, 48, 84, 24, 60])