如何在Python中实现R语言的print(x, digits = n)功能?
在Python中实现R语言
print(x, digits=n)的行为 R语言里print(x, digits=n)的行为规则可总结为:
- 若输入是整数(或小数部分为0的浮点数),直接输出完整整数,不受
digits限制; - 若整数部分的有效位数大于等于
n,则将数字四舍五入为整数后输出; - 若整数部分的有效位数小于
n,则保留总有效位数为n的精度(四舍五入),并自动去除末尾多余的零和不必要的小数点。
以下是Python实现的函数,完全匹配上述规则:
def r_print(x, digits): # 处理负数 negative = False if x < 0: negative = True x = abs(x) # 处理整数或小数部分为0的情况 if x.is_integer(): result = str(int(x)) return '-' + result if negative else result # 用科学计数法解析有效数字的位置 sci = "{:.10e}".format(x) coeff, exp = sci.split('e') exp = int(exp) # 计算整数部分的有效位数 int_digits = exp + 1 if exp >= 0 else 0 if int_digits >= digits: # 四舍五入到整数 rounded = round(x) result = str(int(rounded)) else: # 计算需要保留的小数位数 decimal_places = digits - exp - 1 rounded = round(x, decimal_places) # 格式化字符串,去除末尾多余的零和小数点 rounded_str = str(rounded) if rounded_str.endswith('.0'): rounded_str = rounded_str[:-2] elif '.' in rounded_str: # 先去末尾零,再去可能残留的小数点 stripped = rounded_str.rstrip('0') rounded_str = stripped.rstrip('.') if stripped.endswith('.') else stripped result = rounded_str return '-' + result if negative else result
测试示例
用你给出的R示例验证:
print(r_print(2, digits=2)) # 输出: 2 print(r_print(23, digits=2)) # 输出: 23 print(r_print(23.12, digits=2)) # 输出: 23 print(r_print(2.12, digits=2)) # 输出: 2.1 print(r_print(0.126, digits=2)) # 输出: 0.13 print(r_print(23236.12, digits=6))# 输出: 23236.1 print(r_print(123, digits=2)) # 输出: 123
所有输出结果均与R语言的print(x, digits=n)行为一致。
内容的提问来源于stack exchange,提问作者Simd
相关产品推荐
相关产品推荐

