简体   繁体   English

将列表显示为某个十进制数-Python 3.x

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

I'm having trouble displaying my list in a money format ($0000.00) 我无法以货币格式显示清单($ 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)

If I try 如果我尝试

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

Python returns Python返回

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

You cannot print a list this way, you need to print each list item. 您不能以这种方式打印列表,需要打印每个列表项。 A list comprehension works well here: 列表理解在这里很有效:

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

Because you are trying to do that operation over a list. 因为您正在尝试对列表执行该操作。 You need to do it on each element in your list. 您需要在列表中的每个元素上执行此操作。 Try this: 尝试这个:

Also, I think you want to use %.02f and not %.02d 另外,我认为您想使用%.02f而不是%.02d

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

Output: 输出:

728.08 289.73 117.96 29.70 562.40 255.97 213.55 235.08 436.10 654.54

If you want it just as a list, you can simply do this only: 如果只希望将其作为列表,则只需执行以下操作:

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

You should be using proper Python 3 format strings. 您应该使用正确的Python 3格式字符串。 You can do something like this: 您可以执行以下操作:

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']
"""

You need to put the printing inside your for loop: 您需要将打印内容放入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]))

In 07.02f , 07 says to make sure that the string is at least 7 characters long. 07.02f07表示要确保字符串的长度至少为7个字符。 The 0 is there because if the string is less than 7 characters, that is the character to be used to make it 7 characters. 之所以是0是因为如果字符串少于7个字符,那么该字符就是要用来使其成为7个字符的字符。 02 before the f means that there should be at least two characters after the decimal point. f之前的02表示小数点后至少应有两个字符。 The 0 is there so that if there are fewer than two characters, it will be used to fill it in. 那里是0 ,因此如果少于两个字符,则将使用它来填充它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM