我是python的新手。对于将每个元素读取并存储到一行中的不同数组中,我感到困惑。
例如,我有一个名为“ name_scores.list”的文件
1约翰95
2马克85
3杰西卡75
4嫁98 ...
我想读取此文件并将每一行存储为[数字,名称,分数]的数组。我应该如何编写python脚本?预先感谢您的帮助。
答案 0 :(得分:1)
with open('names_scores.list') as f:
lines = f.readlines() # returns a list of lines, ["1 John 95\n", "2 Mark 88\n", "3 Jessica 75\n", "4 Marry98\n"]
lines = [line.rstrip('\n').split(' ') for line in lines] # remove the trailing \n and split the string up using the spaces
print lines #[[1, John, 95], [2, Mark, 85], [3, Jessica, 75] [4, Marry, 98]]
答案 1 :(得分:1)
with open("name_scores.list") as f:
for line in f:
parts = line.rstrip().split()
print(parts) # A 3-element list
或
with open("name_scores.list") as f:
lines = [line.rstrip().split() for line in f]
print(lines) # A list of 3-element lists
如果您有不想用作分隔符的其他空格(例如,您的名字和姓氏都有),则只想调整parts
(或等效名称)列表的使用方式