Py学习  »  Python

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

Zee Junaid Ahmed • 6 年前 • 1821 次点击  

如何跨多维数组移除重复项: 例子:

[
[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]
]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40004
文章 [ 3 ]  |  最新文章 6 年前
vash_the_stampede
Reply   •   1 楼
vash_the_stampede    7 年前

使用 set 若要消除子列表中的重复项,请检查子列表项是否存在于 res 如果不将这些值附加到 tmp 列出,然后将该列表附加到 物件

res = []
lst = [set(i) for i in lst]

for i in lst:
    tmp = []
    for j in i:
        if not any(j in i for i in res):
            tmp.append(j)
    if tmp:
        res.append(sorted(tmp))

print(res)
# [[125.25, 128, 129], [124.25, 127, 130, 131], [124, 125, 126]]
nosklo
Reply   •   2 楼
nosklo    7 年前
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
Mark
Reply   •   3 楼
Mark    7 年前

也许不是最短的,但像这样的东西会起作用:

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)