首页 > 解决方案 > 如何检查一组元组中的一个元组切片是否在另一组元组中?

问题描述

假设:我有两组元组,任何一组可能不包含相同数量的元组。有什么方法可以在不迭代两组并将一组中的每个条目与另一组的每个条目进行比较的情况下使其工作?

例如,我想知道一个元组的三个条目是否在另一组的任何元组中,这是我尝试过的(示例代码):

s1 = set()
s2 = set()
s1.add(tuple(["a", "b", "c", "e"]))
s1.add(tuple(["d", "e", "f", "h"]))
s2.add(tuple(["a", "b", "c", "d"]))
s2.add(tuple(["d", "e", "f", "g"]))
s2.add(tuple(["m", "n", "o", "p"]))

for x in s1:
    if x[0:3] in s2:
        print(x)

这行不通。

我问是因为这些集合有数千个条目,并且迭代两者都需要太长时间,而且我似乎无法找到一种聪明的方法来做到这一点。

编辑澄清:在我的情况下,每个元组总是有相同数量的条目 4。在我的情况下,我想知道如何检查任意组合 [0:2]、[1:3]、[0:x ]。例如,我需要确认一个元组中的 [0:3] 与另一个元组中的 [0:3] 相同。

标签: python-3.xsettuples

解决方案


你可以为此使用熊猫。Pandas 使用 C 绑定进行了优化,可以非常快速地运行。

df1

0   1   2   3
0   a   b   c   e
1   d   e   f   h
2   x   e   f   h
3   y   u   d   h

df2

0   1   2   3   4   5
0   a   b   c   d   None    None
1   d   e   f   g   None    None
2   m   n   o   p   None    None
3   b   c   d   y   u   d

我在上面假设元组的长度可能不同。

import pandas as pd
df1 = pd.DataFrame([tuple("a", "b", "c", "e"), tuple("d", "e", "f", "h"), tuple("x", "e", "f", "h"), tuple("y", "u", "d", "h") ])
df2 = pd.DataFrame([tuple("a", "b", "c", "d"), tuple("d", "e", "f", "g"), tuple("m", "n", "o", "p"), tuple("b", "c", "d", "y", "u", "d")])


# checks if the first 3 column values are in the second frame
df1[[0,1,2]].isin(df2).any(axis=1)


0     True
1     True
2    False
3     True
dtype: bool

所以它在第二个数据帧的任何位置都匹配 abc、def 和 yud 。您可以推广这种方法来查找第一个数据帧的子集,而不是 cols 0:2。这可能看起来像这样:

for col_max in range(0, len(df1.columns)):
    col_names = [col_index for col_index in range(0, col_max)]
    print(df1[col_names].isin(df2).any(axis=1))

推荐阅读