【问题标题】:Python - Format all float values in a list to the same amount of decimal places [closed]Python - 将列表中的所有浮点值格式化为相同的小数位数[关闭]
【发布时间】:2021-10-14 03:23:53
【问题描述】:

我是编码新手,想根据列表中小数位数最多的浮点值将浮点值列表四舍五入到相同的小数位。例如,说my_list = [23.40, 12.45, 54.21]。如何打印这些值,以便也打印出 23.40 末尾的零?在我的示例中,我知道您可以四舍五入到小数点后 2 位,但如果不是这样(例如 my_list = [23.40, 12.4523, 87.123])怎么办?

真诚地, 新星

【问题讨论】:

  • 将每个浮点数转换为 str 以找出它的小数位数,找到它们的最大值,打印出用这个位数格式化的浮点数。哪一步有问题?

标签: python list rounding


【解决方案1】:

这与将浮点值格式化为具有给定精度的字符串有关。 下面是关于如何以最大小数精度打印所有列表值的分步示例。

my_list = [23.40, 12.4523, 87.123]

# generate a string repr
my_list_str = [str(x) for x in my_list]

# find the max num of decimal places
max_decimal = max([ len(x) - x.find('.') - 1 for x in my_list_str])
print("max_decimal", max_decimal)

# generate a format string
fmt_str = f"%0.{max_decimal}f"
print("fmt_str", fmt_str)

# format all numbers to same decimal places
my_list_str = [fmt_str % x for x in my_list]
print("my_list_str", my_list_str)

# join all strings
res = "[" + ", ".join(my_list_str) + "]"
print(res)

输出

max_decimal 4
fmt_str %0.4f
my_list_str ['23.4000', '12.4523', '87.1230']
[23.4000, 12.4523, 87.1230]

使用高阶函数和更多列表推导可以将代码减少到更少的行,但该示例应提供有关步骤的一般概念。

【讨论】:

  • 输出数字的小数位数为 5。但输入数字的最大小数位数为 4。
  • @leangaurav,不要因为我很喜欢你的方法而放弃你的答案,但是这一行在 Python 3.8.8 中为我吐出了一个错误:my_list_str = [fmt_str % x for x in my_list]。具体来说,ValueError: incomplete format。我从来没有生成像 fmt_str 这样的变量,所以不知道如何建议修复。
  • @xukrao,感谢您的编辑,我错过了那里的 -1。 @wikikikitiki,也感谢您指出,格式说明符中的 f 已被删除。解决了这个问题。
【解决方案2】:

第一步是找到点列表的最大精度。为此,您需要一种方法来查找数字的精度。这是一个可以做到这一点的函数调用(但请参阅帖子底部的注释):

def decimal_precision(x):
    if isinstance(x, int): # if x is an integer there are no decimals
        return(0)
    # if it is a float count the number of values after the decimal
    x_str = str(x)    # start by converting x to a string
    x_split = x_str.split('.') # the split command creates a list, dividing the string at '.'
    n_decimals = len(x_split[1]) # the length of element 1 of x_split will be the number of decimals
    return(n_decimals)

现在我们需要查看列表中哪个条目的小数位数最多

my_list = [23.40, 12.4523, 87.123]

max_precision = 0
for entry in my_list:
    prec = decimal_precision(entry)

    if prec > max_precision:
        max_precision = prec

最后,打印值:

for entry in my_list:
    print(f'{entry:.{max_precision}f}') 
# 23.4000
# 12.4523
# 87.1230

注意:由于floating point arithmetic 的工作原理,这实际上可能比乍一看更难回答。例如,请参阅this post。不过,那篇文章已有大约十年的历史了,而当前版本的 Python(我使用的是 3.8.8)似乎做了一些尝试来改善这一点。上面,我假设使用一种比上面引用的帖子的公认答案中建议的更简单的方法来估计精度。如果您因浮点运算而遇到问题,您可能需要考虑更精细的函数。

【讨论】:

  • 向其他海报致敬,他们的答案比我的更简洁。你提到你是编码新手,所以为了更深入地解释事情,我比我通常编码的方式扩展了更多。希望我更详尽的解释可以帮助您理解他们的代码,这更优雅。
【解决方案3】:

可以使用两种列表推导解决这个问题:一种用于确定小数位数的列表推导,另一种用于构造包含数字的字符串的列表推导。

my_list = [23.40, 12.4523, 87.123]

dec = [len(str(elem).split(".")[1]) for elem in my_list]
str_list = [f'{elem:.{max(dec)}f}' for elem in my_list]

print(str_list)
# Output:
# ['23.4000', '12.4523', '87.1230']

【讨论】:

  • edit您的帖子包含解释
猜你喜欢
  • 2011-12-17
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 2022-11-17
  • 2015-11-17
  • 1970-01-01
  • 2018-07-01
相关资源
最近更新 更多