【问题标题】:Write, Read and Sort List of Lists in python在 python 中写入、读取和排序列表列表
【发布时间】:2020-05-12 07:51:56
【问题描述】:

我有 player_list。我想保存在这样的文件中。

> John, 10
> Raymond, 20
> Oscar, 15

player_list = [['John', 10], ['Raymond', 20], ['Oscar', 15]]
# player_list.append(['Micheal',9])
# print(player_list)
with open('score_test.txt', 'w') as f:
    for item in player_list:
        f.write("{},{} \n".format(item[0], item[1]))

然后读取'score_test.txt'文件并像这样打印 [['约翰',10],['雷蒙德',20],['奥斯卡',15]]

with open('score_test.txt', 'r') as file:
    words = file.read().splitlines()
print(words)

然后追加 ['Micheal',19] 并变成 [['John', 10], ['Raymond', 20], ['Oscar', 15],['Micheal',19]]

然后对其标记进行排序 [['Raymond', 20],['Micheal',19],['Oscar', 15],['John', 10]] 然后再次写入文件。谢谢

【问题讨论】:

  • 你有什么问题?
  • 那么您需要排序或读取文件或写入文件方面的帮助吗?

标签: python list sorting save


【解决方案1】:

player_list = [['John', 10], ['Raymond', 20], ['Oscar', 15]]

with open('a.txt','w') as filee:
  for val in player_list:
    filee.write(f'{val[0]}, {val[1]}')
    filee.write('\n')

d = []

with open('a.txt', 'r') as file:
    words = file.read().splitlines()
    for word in words:
      temp = word.split(',')
      temp[1] = int(temp[1].strip())
      d.append(temp)

d.append(['Micheal',19])

player_list = sorted(d, key=lambda x:x[1], reverse=True)

with open('a.txt','w') as filee:
  for val in player_list:
    filee.write(f'{val[0]}, {val[1]}')
    filee.write('\n')

我想这可能会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 2020-04-17
    • 2011-06-21
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多