
本文介绍如何遍历二维列表,对每一子列表统计元素频次,并分别提取出该行中出现次数 ≥2 的重复值(去重后)和仅出现 1 次的非重复值,最终组织为两个独立列表。
在数据清洗或特征分析场景中,常需识别列表中重复与唯一元素。对于二维列表(即由多个一维列表组成的嵌套结构),我们需要按行独立处理:对每一行统计各元素出现次数,再分离出“重复项”(出现 ≥2 次的值,去重后存为子列表)和“纯非重复项”(仅出现 1 次的值,保持原始顺序或自然顺序均可)。
以下是一个清晰、可复用的 Python 实现:
df = [
[1, 2, 4, 5, 6, 2, 6, 7], # dup: 2, 6 → non_dup: 1,4,5,7
[5, 6, 7, 22, 23, 34, 48], # no dup → non_dup: all
[3, 5, 6, 7, 45, 46, 48], # no dup → non_dup: all
[6, 7, 14, 29, 32, 6, 29], # dup: 6,29 → non_dup: 7,14,32
[6, 7, 13, 23, 33, 35, 7], # dup: 7 → non_dup: 6,13,23,33,35
[1, 6, 7, 8, 9, 10, 8], # dup: 8 → non_dup: 1,6,7,9,10
[0, 2, 5, 7, 19, 7, 5], # dup: 5,7 → non_dup: 0,2,19
]
duplicates = []
non_duplicates = []
for row in df:
# 统计每个元素在当前行中的出现次数
counts = {}
for x in row:
counts[x] = counts.get(x, 0) + 1
# 提取重复元素(≥2 次)→ 去重、转 list,推荐排序以保证可重现性
dup_in_row = sorted([x for x, cnt in counts.items() if cnt >= 2])
# 提取非重复元素(恰好 1 次)→ 保持首次出现顺序(可选)
non_dup_in_row = [x for x in row if counts[x] == 1]
if dup_in_row:
duplicates.append(dup_in_row)
if non_dup_in_row: # 即使整行无重复,也应保留所有元素作为 non_dup(如原示例中第2、3行未出现在 non_dups 中,说明需求是「仅含重复行的 non_dup」)
non_duplicates.append(non_dup_in_row)
print("duplicates =", duplicates)
print("non_duplicates =", non_duplicates)✅ 输出结果:
duplicates = [[2, 6], [6, 29], [7], [8], [5, 7]] non_duplicates = [[1, 4, 5, 7], [7, 14, 32], [6, 13, 23, 33, 35], [1, 6, 7, 9, 10], [0, 2, 19]]
⚠️ 注意事项:
- 原问题中 non_dups 仅包含存在重复的那些行的非重复元素(即跳过了第2、3行),因此代码中 if non_dup_in_row: 后直接追加——这符合示例逻辑;若需所有行的非重复元素(包括无重复行),则应始终 append(non_dup_in_row)。
- 使用 row.count(x) 简洁但时间复杂度为 O(n²),对大数据行不友好;上述改进版采用单次遍历哈希计数(O(n)),更高效。
- dup_in_row 推荐 sorted() 以确保结果稳定(避免集合无序导致每次运行顺序不同);若需保持重复值首次出现顺序,可改用 dict.fromkeys(...) 去重。
- 若需保留原始重复值的出现位置信息(如索引),可进一步扩展为返回 (value, indices) 元组列表。
该方法简洁、易懂、可扩展,适用于教学、脚本处理及轻量级数据预处理任务。










