在python的多维数组中删除重复值

时间:2018-10-22 17:48:50

标签: python python-2.7

如何在多维数组中删除重复项: 例如:

[
[125.25,129,128,129],
[124.25,127,130,131],
[126,126,125,124],
[126,124,130,124]
]

我想要的输出应该是:

[
[125.25,129,128],
[124.25,127,130,131],
[126,125,124]
]

3 个答案:

答案 0 :(得分:1)

也许不是最短的,但是类似的事情会起作用:

arrs = [
[125.25,129,128,129],
[124.25,127,130,131],
[126,126,125,124],
[126,124,130,124]
]

alreadyExisting = []
removedDuplicatesArr = []

for arr in arrs:
    newArr = []
    for i in arr:
        if i not in alreadyExisting:
            alreadyExisting.append(i)
            newArr.append(i)
    if newArr:
        removedDuplicatesArr.append(newArr)

print(removedDuplicatesArr)

答案 1 :(得分:0)

yourlist = [
    [125.25,129,128,129],
    [124.25,127,130,131],
    [126,126,125,124],
    [126,124,130,124]
]
def seen(element, _cache=set()):
    result = element in _cache
    _cache.add(element)
    return result

filtered = ([x for x in sublist if not seen(x)] for sublist in yourlist)
filtered = [sublist for sublist in filtered if sublist] # filter out empty lists

答案 2 :(得分:0)

使用set消除子列表中的重复项,然后检查子列表项是否存在于res中(如果不存在)则将这些值附加到tmp列表中,然后将该列表附加到您的{ {1}}

res