从数据集中移除不匹配项

0 投票
1 回答
697 浏览
提问于 2025-04-18 07:19

我有两个数据集,它们都是嵌套列表的集合。每个列表里的项看起来像这样:list1[i]= [a, x, y, b]list2[j] = [c, x, y, d]。这两个列表的长度不一定相同。我想遍历这两个列表,保持它们的顺序,并去掉那些没有相同 x 值的子列表。最后,我希望得到两个长度相同的列表,并且在每个对应的索引位置,x 值是相同的。

现在我有一段有点乱的代码,它假设 list2 中的 x 值是 list1 中的一个子集(目前这个假设是对的),然后它会去掉那些 x 值不匹配的项。

    len_diff = len(list1) - len(list2)
    if len_diff > 0:
        removed = []
        for (counter, row) in enumerate(list2):
            while list1[counter][1] != list2[counter][1]:
                removed.append(list1.pop(counter))
        new_len_diff = len(list1) - len(list2)
        if new_len_diff < 0:
            raise IndexError('Data sets do not completely overlap')
        else:
            for i in range(new_len_diff):
                removed.append(temp_data.pop())

简单来说,我是在去掉那些 x 值不匹配的项,直到它们开始匹配为止,然后再去掉 list1 中在 list2x 值之后的部分(如果我删得太多了,就会抛出一个异常)。

有没有更好的方法来做到这一点呢?

我现在不一定需要放宽假设,也就是说不一定要保证 list2 中的所有 x 值都在 list1 中,但如果能做到这一点,对我未来处理其他数据会更有帮助。我现在代码中最大的一个问题是,如果 list1 中有空缺,我会把整个列表都删掉。

1 个回答

1

你可以试试这个:

list1 = list2 = [x for x in list1 if x[1] in zip(*list2)[1]]

编辑

根据下面的评论,提问者调整了这个答案,以实现他们想要的效果,具体做法是:

list1 = [x for x in list1 if x[1] in zip(*list2)[1]]
list2 = [x for x in list2 if x[1] in zip(*list1)[1]]

撰写回答