You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找并去除Python列表中numpy.ndarray类型的重复元素

检查并去除numpy数组列表中的重复项

为什么用set会报错?

numpy数组(numpy.ndarray)是可变对象,属于不可哈希类型,而set要求元素必须可哈希才能存储和比对,所以直接用len(chunks[0]) != set(chunks[0])会触发TypeError: unhashable type。

基于Numpy的解决方案

1. 检查是否存在重复项

先将列表中的每个数组展平为一维,再堆叠成一个二维数组,利用np.unique按行去重后,对比去重前后的元素数量即可判断是否有重复:

import numpy as np

# 将chunks[0]中的所有(9,103)数组展平为一维,再堆叠成二维数组
flattened_arrays = np.array([arr.flatten() for arr in chunks[0]])
# 按行去重,获取唯一元素的数量
unique_num = len(np.unique(flattened_arrays, axis=0))
# 判断是否存在重复
has_duplicates = len(chunks[0]) != unique_num
print(f"存在重复项: {has_duplicates}")

2. 去除重复项

借助np.unique的return_index参数,获取唯一元素在原堆叠数组中的索引,再从原列表中提取对应元素即可完成去重(保留首次出现的元素):

# 获取唯一元素的索引
_, unique_indices = np.unique(flattened_arrays, axis=0, return_index=True)
# 按索引排序,维持原列表的顺序
sorted_indices = sorted(unique_indices)
# 提取去重后的数组列表
unique_chunks = [chunks[0][idx] for idx in sorted_indices]
print(f"去重后剩余元素数量: {len(unique_chunks)}")

转张量的实现方式(以PyTorch为例)

转成张量后同样可以实现快速去重,逻辑和Numpy一致,如果后续需要用张量做模型输入,这种方式可以减少数据格式转换的开销:

import torch

# 将数组列表转换为二维张量
tensor_stack = torch.tensor(flattened_arrays)
# 检查重复项
unique_tensor_num = len(torch.unique(tensor_stack, dim=0))
has_duplicates_tensor = len(chunks[0]) != unique_tensor_num
print(f"转张量后检测到重复项: {has_duplicates_tensor}")

# 去除重复项
_, unique_tensor_indices = torch.unique(tensor_stack, dim=0, return_indices=True)
sorted_tensor_indices = sorted(unique_tensor_indices.numpy())
unique_chunks_tensor = [chunks[0][idx] for idx in sorted_tensor_indices]
print(f"张量去重后剩余元素数量: {len(unique_chunks_tensor)}")

注意:单纯做去重操作时,Numpy和PyTorch的效率差异不大,选择哪种方式主要取决于你的后续数据处理流程。

内容的提问来源于stack exchange,提问作者Sal_H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:18:18