我在线阅读了一个文件,并将其转换为JSON。我的结果有效,但是想格式化数字(2345687623,456,875345653345,653

data_file = [{"name":"python", "downloads":23456876, "version": "3.4.2", "version_downloads": 345653 }]


我写了代码来获取值,但是如果我在try内使用except for k in key语句。它不会转换,我也使用了另一种方法,但是得到了cannot convert automatic fields to mamual formatting or something

titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]

i = 0
while i < len(data_file):
    results = []
    for k in key:
        print("{}: {}".format(titles[key.index(k)], data_file[i][k]))
    print()
    i+=1


结果现在看起来像这样:

name: python
downloads: 23456876
latest version: 3.4.2
Latest downloads: 345653


我如何打印downloads为:

downloads: 2,345,676
Latest downloads: 345653

最佳答案

不确定正在做什么索引,但是可以使用isinstance检查int并进行格式化(如果是):

data_file = [{"name":"python", "downloads":23456876, "version": "3.4.2", "version_downloads": 345653 }]


titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]

for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(titles[key.index(k)], val))


输出:

name: python
downloads: 23,456,876
version: 3.4.2
Latest downloads: 345,653


我将使用字典来映射名称并进行查找,而不是建立索引:

titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]
match = dict(zip(key,titles))
for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(match[k], val))


输出:

name: python
downloads: 23,456,876
version: 3.4.2
Latest downloads: 345,653


如果唯一的区别是"version_downloads",则检查if是否可能更简单。

关于python - 如何在循环python中仅格式化项目数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31899363/

10-13 07:12