我有一个带有输出的程序,但是我希望输出是干净的(因此没有方括号或引号),并且我想将数字四舍五入到小数点后两位。
我尝试使用round函数,并尝试对括号使用.join方法,但是它们都不起作用。
import csv
import locale
from pprint import pprint, pformat
import locale
locale.setlocale(locale.LC_ALL, 'Dutch_Netherlands.1252')
gem_names = 'sellerRating', 'Duration', 'ClosePrice', 'OpenPrice'
gemiddelde = {gem_name: 0 for gem_name in gem_names} # Zet de totale op nul.
num_waarden = 0
with open('bijlage.txt', newline='') as bestand:
csvreader = csv.DictReader(bestand, delimiter=';')
for row in csvreader:
for gem_name in gem_names:
gemiddelde[gem_name] += locale.atof(row[gem_name])
num_waarden += 1
for gem_name, total in gemiddelde.items():
gemiddelde[gem_name] = gemiddelde[gem_name] / num_waarden
print ('Dit zijn de gemiddelden:')
pprint(gemiddelde)
这是我得到的输出:
Dit zijn de gemiddelden:
{'ClosePrice': 9.712094266277953,
'Duration': 1.6350826044703595,
'OpenPrice': 3.553561710398435,
'sellerRating': 940.226433430515}
尝试round(gemiddelde)
时出现错误。当我尝试使用.join
时,我的电话号码消失了。谁能帮我使它看起来干净吗?
答案 0 :(得分:1)
在计算过程中最好不要const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}]
}]
}
};
const urls = data.data.results.map(({ urls }) =>
urls.find(({ type }) => type === 'detail')
);
console.log(urls);
,因为四舍五入的误差可能会加起来。相反,只需使用循环和格式字符串来打印值,而不要依赖round
,例如:
pprint
或类似,使用>>> gemiddelte = {'ClosePrice': 9.712094266277953, 'Duration': 1.6350826044703595, 'OpenPrice': 3.553561710398435, 'sellerRating': 940.226433430515}
>>> for key, val in gemiddelte.items():
... print("%15s %6.2f" % (key, val))
...
ClosePrice 9.71
Duration 1.64
OpenPrice 3.55
sellerRating 940.23
:
str.format