社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Zee Junaid Ahmed • 5 年前 • 1557 次点击  

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

[
[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
 
1557 次点击  
文章 [ 3 ]  |  最新文章 5 年前
vash_the_stampede
Reply   •   1 楼
vash_the_stampede    6 年前

使用 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    6 年前
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    6 年前

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

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)