2016-03-10 24 views
0

我無法在貨幣格式($ 0000.00)顯示列表到一定十進制 - Python 3.x都有

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 
+0

您的預期輸出是什麼? –

回答

1

你需要把打印您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個字符的字符。 02f之前表示小數點後至少應有兩個字符。 0是在那裏,如果有少於兩個字符,它將被用來填補它。

+0

謝謝你的解釋! – MikeD

1

因爲您試圖通過列表執行該操作。您需要在列表中的每個元素上執行此操作。試試這個:

另外,我覺得你要使用%.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]) 
1

您應該使用適當的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'] 
""" 
2

你不能這樣打印一個列表,你需要打印每個列表項目。列表理解在這裏很有效:

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

@idjaw是真的,沒有考慮到實際的代碼;) – MattDMo