我遇到了一个问题,在Python中将一个包含多个单词的整个字符串存储到一个列表中。给定一个文件,其中包含有关学生的一些信息,如名字、姓氏、专业和年份,如下所示:
Terrence Jones Computer Science Freshman
Amy Johnson Biology Freshman
Craig Anderson Criminal Justice Sophomore
以此类推。。你知道吗
我的目标是创建一个程序,将这些属性存储到一个列表中。名字和姓氏都有用,但当我到了一些专业比其他专业长的专业时,我就遇到了一个问题。这是我尝试使用的代码:
def main():
survey = open("survey.txt", "r")
lines = survey.readlines()
firstNames = [] # list that stores first names of students that filled out survey
lastNames = [] # list that stores last names of students that filled out survey
major = [] # list that stores the major of students that filled out survey
year = [] # list that stores the classification year of students that filled out survey
for count in lines:
# stores the information from file into the attributes for students
firstNames.append(count.split(' ')[0])
lastNames.append(count.split(' ')[1])
major.append(count.split()[2])
year.append(count.split()[3])
这是我打印专业列表时的输出:
['Computer', 'Biology', 'Criminal', ...]
我期待一个能显示
['Computer Science', 'Biology', 'Criminal Justice', ...]
这也影响了年度榜单,因为如果是一个以上的单词,它会从major停下来的地方回升。有没有人碰巧知道这个问题的解决方法或者我做错了什么?你知道吗
不要指望空格的数目。而是根据列宽对行进行切片:
例如:
相关问题 更多 >
编程相关推荐