【问题标题】:Python: Sorting Tuples in array based off first elementPython:根据第一个元素对数组中的元组进行排序
【发布时间】:2015-05-01 12:46:25
【问题描述】:

我有一个文件,其中的记录 (highscores) 在每一行(带有标题)上存储为 int

在我的 python 项目中,我将记录读入一个数组,然后添加一条记录(只是一个 int),对数组进行排序(添加了新记录),然后用新记录(和标题)覆盖文件- 保持不变)

这是我用于此的相关代码:

highscores = []
with open("highscore.txt", "r") as f:
    f.readline() # Reads header
    for line in f:
        highscores.append(line.strip())

highscores.append(wins)
highscores = sorted(highscores, key=int, reverse=True)
# Print sorted highscores print to file
with open("highscore.txt", "w") as f:
  for val in highscores:
    print(val, file=f)

现在我有一个文件,其中每一行都以int /t string 的形式存储了记录(带有标题)。我没有使用元组读取或排序数组的经验,也不知道如何处理这个问题。谁能让我走上正确的道路或提供解决方案。

我想从我的文件中读取int /t string 记录并将其放入highscores 数组中。然后我想根据作为元组的第一个元素的int 值对数组进行排序(假设我不采用其他方法)。然后用新的highscore 记录覆盖文件。

编辑:

我不应该在我写highscore.append(wins) 时,wins 是一个整数变量我想附加wins 和name(字符串作为我的变量)。

【问题讨论】:

标签: python arrays sorting file-io tuples


【解决方案1】:

你不必改变太多:

 highscores = sorted(highscores, key=lambda s: int(s.split()[0]), reverse=True)

关键功能将接您的线路s。然后它将它拆分,取第一部分,然后将其转换为整数。

【讨论】:

  • 这解决了我的排序问题(很容易解决)谢谢! :) 但我还需要将其更改为分别读取和写入文件。
  • 我相信不需要进行其他更改。这个fix没有做什么?
  • 当我说highscores.append(wins),将wins(它是一个int)放入数组时,我还需要将一个名为name 的变量作为字符串添加到数组中,我该如何追加呢?现在编辑问题更具体。
  • 我可以使用highscores.append(str(wins) + '\t' + name) 来做吗?我要试试,如果一切正常,我会接受你的回答,谢谢你的帮助! :)
  • 试试str(wins) + '\t' + name
猜你喜欢
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2012-08-11
  • 2018-02-09
  • 1970-01-01
相关资源
最近更新 更多