0

我正在寻找创建一个评分系统,并且我正在使用 prettytable 来做到这一点。我将所有分数添加到表中,然后按分数排序。这非常有效,除了当我包含他们的位置(1、2、3、4 等)时,他们混在一起了。

我尝试过的另一种方法是在按分数排序后添加位置,但这会将列添加到表格的右侧,我的目标是将它放在右侧。如果有人可以让我知道如何

a) 覆盖特定列,
b) 停止影响某些列的排序,或
c) 在表格左侧添加新列,

将不胜感激。

from prettytable import PrettyTable

x = PrettyTable()
x.field_names = ["Position", "User", "Score"]


x.add_row([1, "Sam", 42])
x.add_row([2, "Ben", 43])
x.add_row([3, "Alex", 37])
x.add_row([4, "Joe", 54])

x.reversesort = True
y = x.sortby="Score"


print(x.get_string(start=0,end=4))
4

1 回答 1

0

最好将打印与评分分开。

from prettytable import PrettyTable

# A dictionary mapping the user names to scores.

scores = {
    "Sam": 42,
    "Ben": 43,
    "Alex": 37,
    "Joe": 54,
}

# sorted() returns a sorted list from an iterable.
# Since `scores` is now a dict, we need to use `.items()`
# to get pairs out of it.
# The key function accesses the pair's value – the score.
# `reverse=True` is set for obvious reasons.

sorted_user_to_score = sorted(
    scores.items(),
    key=lambda pair: pair[1],
    reverse=True,
)

pt = PrettyTable()
pt.field_names = ["Position", "User", "Score"]

# enumerate() yields pairs of (position, datum) from an iterable.
# It accepts an optional start index parameter – we want positions
# to start from 1, not 0.

for position, (user, score) in enumerate(sorted_user_to_score, 1):
    pt.add_row([position, user, score])

print(pt.get_string(start=0, end=4))

于 2020-02-10T10:59:54.237 回答