【问题标题】:How to display time using a messagebox in python如何在python中使用消息框显示时间
【发布时间】:2015-04-13 13:19:26
【问题描述】:

我正在用 python 设计一个井字游戏,计算用户通过三个级别所需的时间,然后将这个分数保存到一个名为“Player Times.txt”的文件中。我想对每个玩家从低 => 高的次数进行排名。

print('You beaten all three levels and reached the end of the game!')
.windll.user32.MessageBoxW(0, "Hooray you've won the game.","Victory", 1)
ctypes.windll.user32.MessageBoxW(0, str(sum1), "Your Score", 1)
#top_score=str(input('Would you like to see the leaderbooard?'))
MyfileWrite = open('Player Times.txt','a')
MyfileWrite.write(file_info + "'s time is " + str(sum1) + '.' + '\n')
MyfileWrite.close()
print('--------------------')
top_score=str(input('Would you like to see the leaderbooard?'))
print('--------------------')
if (top_score=='yes'):
    MyfileWrite = open('Player Times.txt', 'r')
    file_contents = MyfileWrite.read()
    print(file_contents)
    MyfileWrite.close()

所以这就是当你击败三个级别时会发生的事情。然后您可以查看排行榜,但它只会打印出所有已写入文件的时间。我该怎么做才能对这些时间进行排名?

【问题讨论】:

  • print(file_contents) 将一直​​打印出来。您必须以某种方式对时间进行排序并打印所需的时间。
  • 我该怎么做?

标签: python windows


【解决方案1】:

幸运的是,您正在编写一个漂亮、整洁的文件,以便于解析。它看起来像这样:

Alice's time is 3.2.
Bob's time is 4.6.
Charlie's time is 4.1.
(empty line)

这意味着我们可以这样做:

if top_score.lower().startswith('y'):
    with open('Player Times.txt', 'r') as f:
        print(*sorted(f, key=lambda x: float(x[:-2].split("'s time is ")[1])), sep='')

首先,我们对打开的文件进行排序(它是一个可迭代的,所以我们可以直接这样做),使用分数作为排序键。我们将使用lambda 定义一个带有参数的内联函数,该参数将是文件中的每一行。分数在字符串"'s time is " 之后和最后两个字符".\n" 之前,所以我们截掉最后两个字符,将剩余的字符串拆分为"'s time is ",并将其变成floatsorted() 将使用这个数字来确定正确的顺序。

这为我们提供了与原始文件对象非常相似的内容:list 字符串,只是这次它们被正确排序。一个很好地打印字符串列表的快速方法是使用* 展开列表,并且由于每行末尾已经有一个换行符,我们将告诉print() 使用空字符串作为分隔符而不是通常的空间。

结果:

Alice's time is 3.2.
Charlie's time is 4.1.
Bob's time is 4.6.

sorted() 使用的默认升序在这里有效,但如果你想从高到低排序(例如有积分的游戏),你可以传递关键字参数 reverse=True,例如sorted(['a', 'bbb', 'cc'], key=len, reverse=True) 产生['bbb', 'cc', 'a']

【讨论】:

  • 感谢您的帮助,但我没有收到错误 File "C:/Python32/Final Year Project/Build 11 (Parrell Lists).py", line 316, in <module> print(*sorted(f, key=lambda x: float(x[:-2].split("'s time is ")[1])), sep='') File "C:/Python32/Final Year Project/Build 11 (Parrell Lists).py", line 316, in <lambda> print(*sorted(f, key=lambda x: float(x[:-2].split("'s time is ")[1])), sep='') IndexError: list index out of range 我将之前的代码从 if (top_score==yes) 注释掉到 MyfileWrite.close()。我应该这样做吗?
  • 文本文件看起来和我发布的一样吗,每一行都由用户名、字符串's time is 、一个数字、一个句点和一个换行符组成?编辑您的问题以在代码块中包含文本文件的内容。
  • 终于搞定了!你的评论指出了我的问题。问题以前在我要求输入用户名的代码中,然后将其写入文件,之后时间也写入文件。这产生了类似ben ben's time is x的东西。所以我只是注释掉了之前先写入文件的代码,它工作了!
  • 很高兴听到这个消息!请随意投票/接受此答案以表明它解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多