首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python中写入、读取和排序列表

在python中写入、读取和排序列表
EN

Stack Overflow用户
提问于 2020-05-12 15:51:57
回答 1查看 61关注 0票数 0

我有player_list。我想像这样保存在一个文件中。

代码语言:javascript
复制
> 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‘文件并像这样打印['John',10,'Raymond',20,'Oscar',15]

代码语言:javascript
复制
with open('score_test.txt', 'r') as file:
    words = file.read().splitlines()
print(words)

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

然后将其排序为mark ['Raymond',20,'Micheal',19,'Oscar',15,'John',10],然后再次写入文件。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-12 16:05:33

代码语言:javascript
复制
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')

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61746445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档