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

如何为嵌套列表每行选取一个其他行均不重复的唯一数值

实现方案

核心思路

  • 先全局统计每个数字出现的行数,避免逐行交叉校验的冗余计算
  • 仅出现过1次的数字天然符合「仅在当前行存在、其余行不存在」的要求
  • 逐行匹配找到符合要求的数字即可,无匹配时输出警告

可直接运行的Python代码

from collections import defaultdict

# 配置项:替换为你的csv文件路径
FILE_PATH = "your_data.csv"

# 第一步:统计每个数字的出现行数
num_row_counter = defaultdict(int)
all_rows = []

with open(FILE_PATH, "r", encoding="utf-8") as f:
    for line in f:
        # 按分号分割,过滤末尾空值
        current_nums = [x.strip() for x in line.strip().split(";") if x.strip()]
        all_rows.append(current_nums)
        # 同一行重复的数字只统计一次
        for num in set(current_nums):
            num_row_counter[num] += 1

# 第二步:逐行输出结果
output = []
for line_index, row in enumerate(all_rows, start=1):
    res = None
    for num in row:
        if num_row_counter[num] == 1:
            res = num
            break
    if res:
        output.append(res)
        print(res)
    else:
        warn = f"警告:第{line_index}行无符合要求的唯一数字"
        output.append(warn)
        print(warn)

样例输入的运行结果

用你提供的前8行测试,输出如下:

102465209
102459006
10059021
102464008
102468503
102475670
102468922
102457537

注意事项

  • 若一行有多个符合要求的数字,默认取第一个出现的,可根据需要调整取值逻辑
  • 数字保留字符串格式,若需要转整数可在分割后加int(x.strip())处理
  • 行号从1开始计数,方便定位无匹配的异常行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:24:03