Python - 規定內容列表元素格式的方法


列表是有序且可變的集合。在 Python 中,列表用方括號書寫。透過引用索引號訪問列表項。負索引表示從末尾開始,-1 表示最後一個項。可以透過指定開始和結束範圍來指定索引範圍。在指定範圍時,返回值將是包含指定項的新列表。

示例

 現場演示

# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
# Using list comprehension
Output = ["%.2f" % elem for elem in Input]  
# Printing output
print(Output)
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
# Using map
Output = map(lambda n: "%.2f" % n, Input)  
# Converting to list
Output = list(Output)  
# Print output
print(Output)
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
# Using forrmat
Output = ['{:.2f}'.format(elem) for elem in Input]
# Print output
print(Output)
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]  
# Using forrmat
Output = ['{:.2f}'.format(elem) for elem in Input]  
# Print output
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']

更新日期:2020 年 8 月 6 日

3 千次瀏覽

啟動您的 職業

完成課程並獲得認證

開始
廣告