Python - 格式化给定列表元素的方法
pythonserver side programmingprogramming更新于 2023/10/26 8:15:00
列表是有序且可更改的集合。在 Python 中,列表用方括号书写。您可以通过引用索引号来访问列表项。负索引表示从末尾开始,-1 表示最后一项。您可以通过指定范围的开始位置和结束位置来指定索引范围。指定范围时,返回值将是包含指定项目的新列表。
示例
# 列表初始化 Input = [100.7689454, 17.232999, 60.98867, 300.83748789] # 使用列表推导式 Output = ["%.2f" % elem for elem in Input] # 打印输出 print(Output) # 列表初始化 Input = [100.7689454, 17.232999, 60.98867, 300.83748789] # 使用 map Output = map(lambda n: "%.2f" % n, Input) # 转换为列表 Output = list(Output) # 打印输出 print(Output) # 列表初始化 Input = [100.7689454, 17.232999, 60.98867, 300.83748789] # 使用格式 Output = ['{:.2f}'.format(elem) for elem in Input] # 打印输出 print(Output) # 列表初始化 Input = [100.7689454, 17.232999, 60.98867, 300.83748789] # 使用格式 Output = ['{:.2f}'.format(elem) for elem in Input] # 打印输出 print(Output)
输出
['100.77', '17.23', '60.99', '300.84'] ['100.77', '17.23', '60.99', '300.84'] ['100.77', '17.23', '60.99', '300.84'] ['100.77', '17.23', '60.99', '300.84']