【问题标题】:How to intersect a lot of sets [duplicate]如何相交很多集合[重复]
【发布时间】:2016-05-26 09:09:25
【问题描述】:

我有一套

{1, 2, 3, 4}
{2, 3, 4, 5}
{3, 4, 5, 6}
{4, 5, 6, 7}
{5, 6, 7, 8} 

我需要从第一个开始相交集合。我的意思是我应该相交

{1, 2, 3, 4}
{2, 3, 4, 5}
{3, 4, 5, 6}

下一个

{2, 3, 4, 5}
{3, 4, 5, 6}
{4, 5, 6, 7}

{3, 4, 5, 6}
{4, 5, 6, 7}
{5, 6, 7, 8}

我怎样才能在循环中做到这一点?我知道我可以使用set1 & set2 & set3,但我不知道如何使用下一个set2 & set3 & set4 等?

【问题讨论】:

  • 我不明白你到底是什么意思?这些集合在列表中吗?

标签: python set intersect


【解决方案1】:

首先,您需要一个列表中的所有集合,然后使用zip-函数并行遍历您的列表:

sets = [
    {1, 2, 3, 4},
    {2, 3, 4, 5},
    {3, 4, 5, 6},
    {4, 5, 6, 7},
    {5, 6, 7, 8},
]

for s1, s2, s3 in zip(sets, sets[1:], sets[2:]):
    print(s1 & s2 & s3)

或更笼统地说:

AMOUNT_OF_SETS_TO_INTERSECT = 3
for sets_to_intersect in zip(*(sets[i:] for i in range(AMOUNT_OF_SETS_TO_INTERSECT))):
    print(set.intersection(*sets_to_intersect))

【讨论】:

  • 但是如果我有 60 套,我该怎么做呢?
  • 60 组相交?
  • 我有 60 个集合,我想每 3 个集合相交:set1 & set2 & set3, set2 & set3 & set4, set3 & set4 & set5, ...
  • 所以你有一个列表 sets 有 60 个条目。有什么问题?
  • 我应该使用sets[1:], sets[2:], sets[3:]等吗?有什么办法让它更具可读性吗?
【解决方案2】:

如果你正在寻找方法来做多个集合的交集,那么this page 有答案,它基本上告诉你使用set.intersection() 函数

如果你不知道如何将你的集合放在一个列表中然后遍历它,这是一个不同的问题,这是基本的 Python。

在 Python 中,您可以将对象(包括集合)放在一个列表中,并按如下方式遍历它:

# Build the list of sets
set_list = []
for i in range(1, 6):
    set_list.append(set([i, i+1, i+2, i+3]))

# Now set_list contains the set (1,2,3,4), (2,3,4,5), ..., (5,6,7,8)

# Traverse and do set intersection
for i in range(len(set_list)-2):
    intersection = set.intersection(set_list[i], set_list[i+1], set_list[i+2])
    print(intersection)

# Will print:
# set([3, 4])
# set([4, 5])
# set([5, 6])

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多