【问题标题】:Formatting over a list to include commas and spacing格式化列表以包含逗号和空格
【发布时间】:2020-04-26 20:11:04
【问题描述】:

我正在使用这个字典,使用 mark_planets() 为每个行星附加另一个值,然后打印出一个具有定义规范的表格。

############## 跳过这个,这只是为了让公式正确运行
sol = {"Uranus": [2750, 3000, 2880], "Mercury": [46, 70, 57], "Earth": [147, 152, 150], "Venus": [107, 109, 108],
       "Mars": [205, 249, 228], "Saturn": [1350, 1510, 1430], "Jupiter": [741, 817, 779],
       "Pluto": [4440, 7380, 5910], "Neptune": [4450, 4550, 4500]}

status = [True, True, True, True, True, True, True, False, True]

def mark_planets(planets, stat):
    idx = 0
    for planet in planets:
        if stat[idx]:
            planets[planet].append("Planet")
            idx += 1
        else:
            planets[planet].append("Dwarf")
            idx += 1
################下面是问题
def display_planets(sol):
    print("{:>10} {:>10} {:>15} {:>15} {:>15}".format("planet", "status", "nearest", "furthest", "average"))
    print("{:-^69s}".format("-"))
    for planet in sol:
        print("{:>10} {:>10} {:>15} {:>15} {:>15}".format(planet, sol[planet][3], sol[planet][0], sol[planet][1],sol[planet][2]))

如图所示,我有正确的输出间距,但我需要在数字之间使用逗号格式化 value[0],[1],[2]。我不确定如何将逗号格式化为字符串并保持正确的间距以使其正确打印。

下面是我目前的输出。

    planet     status         nearest        furthest         average
---------------------------------------------------------------------
    Uranus     Planet      2750000000      3000000000      2880000000
   Mercury     Planet        46000000        70000000        57000000
     Earth     Planet       147000000       152000000       150000000
     Venus     Planet       107000000       109000000       108000000
      Mars     Planet       205000000       249000000       228000000
    Saturn     Planet      1350000000      1510000000      1430000000
   Jupiter     Planet       741000000       817000000       779000000
     Pluto      Dwarf      4440000000      7380000000      5910000000
   Neptune     Planet      4450000000      4550000000      4500000000``

只是将逗号添加到数字是我正在努力解决的问题。感谢您的帮助。

【问题讨论】:

  • 由于数字很大,我建议使用科学记数法,例如'{:.3e}'.format(num) 会将 2750000000 格式化为 '2.750e+09'
  • 嗨,Noah,感谢您的提示,但规范概述了以这种格式使用逗号。

标签: python list dictionary printing format


【解决方案1】:

答案来源于Ian Schneider's答案

您可以在最后将, 传递给您的整数格式规范,因此它的内容如下:

some_value = 12345678
"{:>15,}".format(some_value)

【讨论】:

    猜你喜欢
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    相关资源
    最近更新 更多