【发布时间】:2020-03-23 16:48:03
【问题描述】:
我在将包含多个单词的整个字符串存储到 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', ...]
这也影响了年份列表,因为如果它超过一个单词,它会从专业停止的地方开始。有没有人碰巧知道解决这个问题或我做错了什么?
【问题讨论】: