Py学习  »  Python

python:从对象列表中删除几乎重复的内容

flaviojohnson • 6 年前 • 1601 次点击  

如何删除下列元组列表中的所有元组 其中只有一个特定索引不重复 ?在这种情况下,我需要删除每个元组的第二个值(也称为索引1)的重复项。

[(1051,97),(1051,132),(1048,132),(1048,283),(1048,438)]
                 ^^^        ^^^

期望输出:

[(1051,97),(1051,132),(1048,283),(1048,438)]

能够保持上述期望输出中所示的一阶优先级的加分。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40680
 
1601 次点击  
文章 [ 4 ]  |  最新文章 6 年前
DYZ
Reply   •   1 楼
DYZ    6 年前

建立一个反向字典。由于字典键总是唯一的,因此会自然地消除重复:

l = [(1051,97),(1051,132),(1048,132),(1048,283),(1048,438)]
[(x,y) for y,x in {y:x for x,y in l}.items()]
#[(1051, 97), (1048, 132), (1048, 283), (1048, 438)]

这种解决办法不能维持秩序。

RafaelC
Reply   •   2 楼
RafaelC    6 年前

使用 pandas

df = pd.DataFrame(l)
df.loc[df[1].drop_duplicates().index].values.tolist()
Timothy Jannace
Reply   •   3 楼
Timothy Jannace    6 年前
lst = [(1051,97),(1051,132),(1048,132),(1048,283),(1048,438)]
lst = list(reversed([(v, k) for k, v in {t[1]: t[0] for t in reversed(lst)}.items()]))
print(lst)
# [(1051, 97), (1051, 132), (1048, 283), (1048, 438)]
slider
Reply   •   4 楼
slider    6 年前

您可以维护一组在迭代时遇到的所有index 1元素,并且只有在没有遇到其index 1元素时,才能在最终结果中包含元组:

lst = [(1051,97),(1051,132),(1048,132),(1048,283),(1048,438)]

s = set()
res = []
for i, j in lst:
    if j not in s:
        s.add(j)
        res.append((i,j))

print(res)
# [(1051, 97), (1051, 132), (1048, 283), (1048, 438)]