在 python 中写入、读取和排序列表列表
Write, Read and Sort List of Lists in python
我有 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' 文件并像这样打印
[['John', 10], ['Raymond', 20], ['Oscar', 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]] 然后再次写入文件。谢谢
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')
我想这可能对你有帮助。
我有 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' 文件并像这样打印 [['John', 10], ['Raymond', 20], ['Oscar', 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]] 然后再次写入文件。谢谢
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')
我想这可能对你有帮助。