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

如何在NumPy 1.24中解决二维列表去重问题?

解决NumPy 1.24中二维不等长子列表去重报错问题

问题描述

你有一个包含大量重复子列表的二维列表,子列表长度不一致,示例如下:

sta_list = [[31, 30, 11, 3, 1, 0], [31, 30, 11, 3, 1, 0], ……, [34, 33, 1, 0], ……]

在NumPy 1.22版本中,可通过np.unique(np.array(sta_list))实现去重,但在Python 3.11搭配NumPy 1.24的环境中执行会触发报错:

Traceback (most recent call last):
  File "C:\Users\yy\AppData\Roaming\JetBrains\IntelliJIdea2023.3\plugins\python\helpers-pro\pydevd_asyncio\pydevd_asyncio_utils.py", line 114, in _exec_async_code
    result = func()
             ^^^^^^
  File "<input>", line 1, in <module>
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (396,) + inhomogeneous part.

原因是NumPy 1.24对非均匀形状数组的处理更严格,不再允许直接对不等长的子列表数组执行np.unique。

解决方案

方法1:Python原生集合去重(简单高效)

由于列表不可哈希,先将每个子列表转为元组,利用集合自动去重,再转回列表。如果需要保留子列表的首次出现顺序,可使用dict.fromkeys:

# 不保留顺序
unique_sta = list(set(tuple(sub) for sub in sta_list))
# 保留首次出现的顺序
unique_sta = list(dict.fromkeys(tuple(sub) for sub in sta_list))
# 转回列表格式(如果需要)
unique_sta = [list(item) for item in unique_sta]

方法2:NumPy结构化数组去重

将子列表转为元组后创建结构化数组,再用np.unique处理:

import numpy as np
# 转换为元组列表并创建结构化数组
structured_arr = np.array([tuple(sub) for sub in sta_list], dtype=object)
# 去重
unique_arr = np.unique(structured_arr)
# 转回二维列表
unique_sta = [list(item) for item in unique_arr]

方法3:利用Pandas去重

通过Pandas的Series处理不等长序列,实现去重:

import pandas as pd
# 将子列表转为元组后创建Series
s = pd.Series(sta_list).apply(tuple)
# 去重并转回列表
unique_sta = [list(item) for item in s.unique()]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:12:42