从多个列表中删除同一索引的重复项

-1 投票
3 回答
31 浏览
提问于 2025-04-12 19:59

我知道在Python中有一个内置函数np.unique(),可以用来去掉数组列表中的重复项,或者把数组列表转换成字典再转回数组列表。

但是,我遇到的问题是这样的:

我有三个列表:

l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'j', 'a'] l2 = ['b', 'a', 'b', 'd', 'e', 'f', 'b', 'j', 'b'] l3 = ['c', 'a', 'a', 'd', 'e', 'f', 'c', 'j', 'c']

我想知道有没有内置函数可以去掉重复的"a, b, c",其中"a"在列表l1中,"b"在列表l2中,"c"在列表l3中,并且"a, b, c"在同一个索引位置上。

在这个例子中,应该去掉三个列表中索引为8和6的项。

谢谢你的帮助。

3 个回答

0

如果我理解正确的话,你可以这样做:

l1 = ["a", "b", "c", "d", "e", "f", "a", "j", "a"]
l2 = ["b", "a", "b", "d", "e", "f", "b", "j", "b"]
l3 = ["c", "a", "a", "d", "e", "f", "c", "j", "c"]

out, found = [], False
for t in zip(l1, l2, l3):
    if t == ("a", "b", "c"):
        if found is False:
            out.append(t)
            found = True
    else:
        out.append(t)

l1, l2, l3 = map(list, zip(*out))
print(f"{l1=}\n{l2=}\n{l3=}")

输出结果是:

l1=['a', 'b', 'c', 'd', 'e', 'f', 'j']
l2=['b', 'a', 'b', 'd', 'e', 'f', 'j']
l3=['c', 'a', 'a', 'd', 'e', 'f', 'j']
1

如果我理解你的问题没错的话,每个列表虽然有不同的独特值,但在对每个列表使用 np.unique 时,返回的 unique_indicesunique_counts 是一样的。我们可以利用这一点,只对一个列表运行 np.unique,并把 return_countsreturn_index 设置为 True,然后使用它的输出结果。

uni, ind, cts = np.unique(l1, return_counts = True, return_index = True)
no_repeat_l1 = np.array(l1)[ind[cts == 1]]
no_repeat_l2 = np.array(l2)[ind[cts == 1]]
no_repeat_l3 = np.array(l3)[ind[cts == 1]]

撰写回答