[英]Comma separated List formatting
我希望在列表中创建一个包含 20 个随机数的列表,但希望打印这些数字以逗号分隔的结果。 当我想格式化下面的主要列表时出现错误。
res = ('{:,}'.format(Principal))
TypeError: unsupported format string passed to list.__format__.
我怎样才能解决这个问题?
def inventory(i,j):
import random
Amount = random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)
return Amount
def main():
Principal = inventory(100000, 1000000)
res = ('{:,}'.format(Principal))
print('\nInventory:\n', + str(res))
minAmt = min(Principal)
maxAmt = max(Principal)
res1 = ('{:,}'.format(minAmt))
res2 = ('{:,}'.format(maxAmt))
print('\nMin amount:' + str(res1))
print('\nMax amount:' + str(res2))
if __name__ == '__main__':
main()
您正在寻找str.join
。 例如
res = ','.join(map(str, Principal))
此外,以下不是有效的语法:
print('\nInventory:\n', + str(res))
+
那里是非法的。
Principal
是金额列表, ,
不是列表的格式说明符。 单独打印每个金额:
import random
def inventory(i,j):
return random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)
amounts = inventory(100000, 1000000)
print('\nInventory:\n')
for amount in amounts:
print(f'{amount:,}')
print(f'\nMin amount: {min(amounts):,}')
print(f'\nMax amount: {max(amounts):,}')
输出:
Inventory:
283,250
904,600
807,800
297,850
314,000
557,450
167,550
407,475
161,550
684,225
787,025
513,975
252,750
217,500
394,200
777,475
621,575
888,625
895,525
846,650
Min amount: 161,550
Max amount: 904,600
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.