簡體   English   中英

將列表顯示為某個十進制數-Python 3.x

[英]Displaying A List to a Certain Decimal - Python 3.x

我無法以貨幣格式顯示清單($ 0000.00)

priceList = [1,2,3,4,5,6,7,8,9,10]
    for i in range (10):
    priceList[i] = random.uniform(1,1000)
print (priceList)

如果我嘗試

print ('%.02d' %(priceList))

Python返回

TypeError: %d format: a number is required, not list

您不能以這種方式打印列表,需要打印每個列表項。 列表理解在這里很有效:

[print('%.02f' % i) for i in priceList]

因為您正在嘗試對列表執行該操作。 您需要在列表中的每個元素上執行此操作。 嘗試這個:

另外,我認為您想使用%.02f而不是%.02d

print(' '.join('%.02f' % (x) for x in priceList))

輸出:

728.08 289.73 117.96 29.70 562.40 255.97 213.55 235.08 436.10 654.54

如果只希望將其作為列表,則只需執行以下操作:

print(['%.02f' % x for x in priceList])

您應該使用正確的Python 3格式字符串。 您可以執行以下操作:

import random
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
    priceList[i] = random.uniform(1,1000)

moneyList = list(map(lambda x: "${:07.02f}".format(x), priceList))
print(moneyList)  # => output:
"""
['$294.90', '$121.71', '$590.29', '$45.52', '$319.40', '$189.03', '$594.63', '$135.24', '$645.56', '$954.57']
"""

您需要將打印內容放入for循環中:

priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range(10):
    priceList[i] = random.uniform(1,1000)
    print("${:07.02f}".format(priceList[i]))

07.02f07表示要確保字符串的長度至少為7個字符。 之所以是0是因為如果字符串少於7個字符,那么該字符就是要用來使其成為7個字符的字符。 f之前的02表示小數點后至少應有兩個字符。 那里是0 ,因此如果少於兩個字符,則將使用它來填充它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM