用python编写、读取和排序列表

2024-09-28 17:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有球员名单。我想像这样保存在一个文件中

> 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]]然后再次写入文件。谢谢


Tags: 文件testtxtaswithopenitemjohn
1条回答
网友
1楼 · 发布于 2024-09-28 17:23:07

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')

我想这可能对你有帮助

相关问题 更多 >