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

如何用Excel或PowerShell将18.7万条10位数字分组为连续范围

高效合并连续数字序列为范围的解决方案

针对187000条10位数字的批量处理需求,以下两种方案可替代手动Excel操作,大幅提升效率:

方案一:Excel Power Query 可视化操作(适合熟悉Excel的用户)

无需复杂公式,通过Power Query的分组功能自动识别连续序列:

  1. 将所有数字整理到Excel单列(A1设为表头「数字」,A2开始为数据)
  2. 选中数据区域,点击「数据」→「从表格/区域」(勾选「我的表格有标题」),进入Power Query编辑器
  3. 点击「转换」→「排序」,按「数字」列升序排列(必须排序,否则无法正确识别连续)
  4. 添加索引列:「添加列」→「索引列」→「从0开始」
  5. 添加自定义列「是否连续」,输入公式:
    = if [索引] = 0 then true else [数字] = #"添加索引"[数字]{[索引]-1} + 1
    
  6. 添加自定义列「分组ID」,输入公式生成连续序列的分组标识:
    = List.Accumulate(List.Range(#"添加自定义"[是否连续], 1), 0, (state, current) => if current then state else state + 1)
    
    手动将第一行的「分组ID」值改为0
  7. 点击「转换」→「分组依据」,设置:
    • 分组依据:「分组ID」
    • 新列名:「范围」
    • 操作:「所有行」
  8. 添加自定义列生成最终范围文本:
    = if List.Count([范围][数字]) = 1 then Text.From(List.First([范围][数字])) else Text.From(List.First([范围][数字])) & "-" & Text.From(List.Last([范围][数字]))
    
  9. 删除「分组ID」「范围」列以外的所有列,点击「主页」→「关闭并上载」,结果将导出到新工作表

方案二:Python脚本(适合大数据量快速处理)

对于18万条数据,Python处理速度远快于Excel,步骤如下:

文本文件输入版

假设你的数字每行一个存放在data.txt中,运行以下脚本:

# 读取并整理数据
with open('data.txt', 'r', encoding='utf-8') as f:
    # 过滤无效行并转为整数,再排序
    numbers = sorted(int(line.strip()) for line in f if line.strip().isdigit())

if not numbers:
    print("未读取到有效数字数据")
else:
    ranges = []
    start = end = numbers[0]
    # 遍历识别连续序列
    for num in numbers[1:]:
        if num == end + 1:
            end = num
        else:
            # 保存当前序列
            ranges.append(str(start) if start == end else f"{start}-{end}")
            start = end = num
    # 处理最后一组序列
    ranges.append(str(start) if start == end else f"{start}-{end}")

# 保存结果到output.txt
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(ranges))

Excel/CSV输入版

如果数据在Excel中,先将数据导出为data.csv(仅保留数字列),使用以下脚本:

import csv

numbers = []
# 读取CSV文件
with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    next(reader)  # 跳过表头行
    for row in reader:
        if row[0].isdigit():
            numbers.append(int(row[0]))
numbers = sorted(numbers)

# 以下逻辑和文本版一致
ranges = []
start = end = numbers[0]
for num in numbers[1:]:
    if num == end + 1:
        end = num
    else:
        ranges.append(str(start) if start == end else f"{start}-{end}")
        start = end = num
ranges.append(str(start) if start == end else f"{start}-{end}")

with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(ranges))

运行脚本后,结果会保存到output.txt中,格式完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:55:17