如何从列表中删除相似列表。如何从列表中删除重复项

时间:2020-12-30 08:09:28

标签: python

index=[[25, 0], [25, 1], [25, 0], [25, 4], [25, 1], [25, 4], [56, 2], [56, 3]]
for x in range(0,len(index)):
    for y in range(x+1,len(index)):
        if index[x][-1]==index[y][-1]:
            index.remove(index[y])
print(index)

出现以下错误:

 if index[x][-1]==index[y][-1]: IndexError: list index out of range

3 个答案:

答案 0 :(得分:1)

您正在遍历一个列表并同时删除同一个列表......它用完了循环开始的索引。复制一份清单,然后运行它。

稍加修改的代码。

index=[[25, 0], [25, 1], [25, 0], [25, 4], [25, 1], [25, 4], [56, 2], [56, 3]]
index_for_loop = index.copy()
for x in range(0,len(index_for_loop)):
    for y in range(x+1,len(index_for_loop)):
        if index_for_loop[x]==index_for_loop[y]:
            index.remove(index_for_loop[y])
print(index)

给出输出

[[25, 0], [25, 1], [25, 4], [56, 2], [56, 3]]

答案 1 :(得分:1)

单线:

index = list(map(list, (set(tuple(a) for a in index))))

给予

[[25, 4], [25, 0], [56, 3], [56, 2], [25, 1]]

列表在 Python 中是不可散列的,因此您需要先将它们转换为 tuple

答案 2 :(得分:0)

您可以尝试以下方法

index = [[25, 0], [25, 1], [25, 0], [25, 4], [25, 1], [25, 4], [56, 2], [56, 3]]

lst = []

for i in range(len(index)):
    if index[i] not in lst:
        lst += [index[i]]

print(lst)
>>> [[25, 0], [25, 1], [25, 4], [56, 2], [56, 3]]