python 如何匹配两个长度相同的列表

luaexgnf  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(189)

我有两个相同长度的列表.我想在df和df2中找到一个匹配.

df = [[[1, 5,7,9,12,13,17],
   [2,17,18,23,32,34,45],
   [3,5,11,33,34,36,45]],
  [[6,21,22,50,56,58,72],
  [7,5,12,13,55,56,74],
  [8,23,24,32,56,58,64]]]

    df2 = [[[100,5,12,15,27,32,54],
    [120,10,17,18,19,43,55],
    [99,21,32,33,34,36,54]],
   [[41,16,32,45,66,67,76],
    [56,10,11,43,54,55,56],
    [77,12,16,18,19,21,23]]]

我希望我的输出像这样或类似。

output = [[[[5,12,],[17]],
      [[17,18],[32,34,36]]],
      [[[55,56],[32]],[[56]]]
of1yzvn4

of1yzvn41#

所以这个问题很难,因为为了比较数组,你需要计算所有可能先出现的序列,所以当你处理大数组时,这个任务会很长。
我的方法没有为了简单而进行任何优化,我试图坚持基本的for循环,只是粗暴地强制通过它。
首先,我将计算两个数组的所有可能组合,并将它们存储在两个列表中(sequences_1sequences_2)。
然后,我将比较所有序列并将匹配存储在一个集合中。使用集合将自动删除所有重复项。Matches现在保存了两个数组的所有可能匹配项。

df = [
    [[1, 5, 7, 9, 12, 13, 17], [2, 17, 18, 23, 32, 34, 45], [3, 5, 11, 33, 34, 36, 45]],
    [[6, 21, 22, 50, 56, 58, 72], [7, 5, 12, 13, 55, 56, 74], [8, 23, 24, 32, 56, 58, 64]],
]

df2 = [
    [[100, 5, 12, 15, 27, 32, 54], [120, 10, 17, 18, 19, 43, 55], [99, 21, 32, 33, 34, 36, 54]],
    [[41, 16, 32, 45, 66, 67, 76], [56, 10, 11, 43, 54, 55, 56], [77, 12, 16, 18, 19, 21, 23]],
]

sequences_1 = []

for el in df:
    for lis in el:
        length = len(lis)
        for i in range(0, length):
            for n in range(i + 1, length + 1):
                sequences_1.append(lis[i:n])

sequences_2 = []

for el in df2:
    for lis in el:
        length = len(lis)
        for i in range(0, length):
            for n in range(i + 1, length + 1):
                sequences_2.append(lis[i:n])

matches = set()

for seq_1 in sequences_1:
    for seq_2 in sequences_2:
        if seq_1 == seq_2:
            matches.add(tuple(seq_1))
print(matches)

作为匹配项,我得到:

{(5,), (11,), (17,), (23,), (17, 18), (32,), (55, 56), (56,), (5, 12), (34, 36), (34,), (33, 34, 36), (55,), (33, 34), (12,), (18,), (21,), (33,), (36,), (45,)}

这将保存您作为可能输出呈现的所有匹配项,以及您在发布问题时错过的其他匹配项。

相关问题