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

Python如何实现整数转10间隔区间字符串,如输入1返回"1-10"

实现整数转10间隔区间字符串的方案

Python没有专门实现该需求的内置标准库函数,自定义实现成本极低,可直接适配pandas处理场景:

需求效果:输入1返回"1-10",输入27返回"21-30"

基础自定义函数实现

def convertnumtorange(n: int) -> str:
    lower = ((n - 1) // 10) * 10 + 1
    upper = lower + 9
    return f"{lower}-{upper}"

效果验证:

  • convertnumtorange(1) 输出:"1-10"
  • convertnumtorange(27) 输出:"21-30"
  • convertnumtorange(105) 输出:"101-110"

Pandas DataFrame 场景适配

小数据量方案:apply映射

适合数据量小于10万的场景,写法简单直观:

import pandas as pd

# 替换代码中的value为你存储数值的列名
df['range'] = df['value'].apply(convertnumtorange)

大数据量方案:向量化运算

处理10万以上数据时性能远高于逐行调用函数,无需自定义函数:

# 替换代码中的value为你存储数值的列名
df['range'] = ((df['value'] - 1) // 10 * 10 + 1).astype(str) + '-' + (((df['value'] - 1) // 10 * 10) + 10).astype(str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:54:09