首页 > 解决方案 > 在python中打印一种矩阵

问题描述

我必须打印这个 Python 代码:

Placement     Name     Won    Played   Percent Won
1             B Borg    5       10         0.5
2             J Smith   3       6          0.5           
3
.
.
.

播放器的数量会有所不同,因为播放器是从 txt 文件导入的。第一行(位置、名称等)是不变的。

我如何使用格式化来做到这一点?或者,如果有更简单的方法。玩家的信息应该如上面的示例代码所示对齐。

编辑:

def showLeaderboard(players): 
    print()
    print("Placement, Name, Won, Played, Percent Won")
    position = 1
    for i in players:
        print(position, end=" ")
        i.showPlayerInfo()
        position += 1

def readPlayers(): 
    fileplacement = "leads to a directory"
    if os.path.exists(fileplacement) and os.path.getsize(fileplacement) > 6:
        txtinfo = open("players.txt", "r")
        players = []
        for row in txtinfo:
            infoplayers = row.split(",")
            players.append(Spelare(infoSpelare[0], float(infoSpelare[3]), int(infoSpelare[1]), int(infoSpelare[2]))) # "players" is a class, the rest is to import from my txt-file
        return players
    else:
        print("players.txt does not seem to exist or contains unreasonables.")
        raise SystemExit(0)

标签: python-3.xformat

解决方案


您要使用的是以下字符串方法:

  • 只是
  • 调整
  • 中央

这是一个帮助您入门的示例:

import sys


player_data = {
    "Name": "B Borg",
    "Placement": 1,
    "Won": 5,
    "Played": 10,
    "Percent Won": 0.5
}


def print_format(k, val):
    if k == "Name":
        sys.stdout.write(val.ljust(20, ' '))
    if k == "Placement":
        sys.stdout.write(val.ljust(15, ' '))
    if k == "Won":
        sys.stdout.write(val.center(10, ' '))
    if k == "Played":
        sys.stdout.write(val.center(20, ' '))
    if k == "Percent Won":
        sys.stdout.write(val.center(10, ' '))


# Print the header
[print_format(k, k) for k in player_data.keys()]
print()

# Print the data:
[print_format(k, str(v)) for k, v in player_data.items()]
print()
(venv) [ttucker@zim bot]$ python justify.py 
Name                Placement         Won           Played       Percent Won
B Borg              1                  5              10            0.5    

推荐阅读