python-3.x - 在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)
解决方案
您要使用的是以下字符串方法:
- 只是
- 调整
- 中央
这是一个帮助您入门的示例:
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
推荐阅读
- lua - 没有括号的函数lua c ++
- c# - 如何将字符串转换为 blazor 中的组件?
- javascript - 如何在vuejs中以编程方式将类添加到相应输入元素上的焦点事件?
- r - 未能使用 diagrammeR 的 grViz 将字符串替换与 sprintf 和类似 Razor 的语法结合起来用于流程图
- sql - 在oracle中将具有多行的单列转换为多列
- django - Django 函数包含多个带返回的函数
- google-api - 如果我的 GSuite 帐户被撤销,我如何访问“OAuth 同意屏幕”?
- python - 在熊猫数据框中创建不同变量的滚动总和和平均值
- android-intent - Android API 30 getPackageManager.resolveActivity() 使用 ACTION_VIEW 返回 null
- flutter - Flutter:未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'id'。接收方:null 尝试调用:id