【发布时间】:2019-10-02 10:58:30
【问题描述】:
所以,我有一个包含以下信息的文本文件:
student_num1 student_name1 student_grade1
student_num2 student_name2 student_grade2
student_num3 student_name3 student_grade3
我想要做的是我想将此文本文件的每一行作为具有这种格式的字典条目:
students = { student_num1: [student_name1, student_grade1], student_num2: [student_name2, student_grade2], student_num3: [student_name3, student_grade3] }
基本上,该行的第一个字符串应该是键,它旁边的 2 个字符串是值。但我不知道如何让 python 分隔每一行中的字符串并将它们分配为字典的键和值。
编辑: 所以,我尝试了一些代码:(我看到了你所有的解决方案,我认为它们肯定会起作用,但我也想学习创建我的解决方案,所以如果你能检查我的,我将非常感激!)
for line in fh:
line = line.split(";")
student_num = line[0]
student_name = line[1]
student_grade = line[2]
count =+ 1
direc[student_num] = [student_name,student_grade]
student_num = "student_num" + str(count)
student_grade = "student_grade" + str(count)
student_name = "student_name" + str(count)
print(direc)
问题是我在第 10 行或这部分“student_name = line[1]”上收到列表索引超出范围的错误
编辑:谢谢大家!您建议的每一个解决方案都有效!我也修复了我自己的解决方案。这是固定的(正如@norok2 所建议的那样):
for line in fh:
line = line.split(" ")
student_num = line[0]
student_name = line[1]
student_grade = line[2]
count =+ 1
direc[student_num] = [student_name,student_grade]
student_num = "student_num" + str(count)
student_grade = "student_grade" + str(count)
student_name = "student_name" + str(count)
【问题讨论】:
-
您搜索了什么,找到了什么?基于此,您尝试了什么,又是如何失败的?
-
@tripleee 我已经搜索了一段时间,但似乎找不到解决方案。我的想法是我想尝试将每一行作为一个列表,然后将该列表用作我的字典的条目,但问题是 1:我不知道分隔每一行并使每一行成为列表的正确语法和 2:我也不知道如何让 python 将列表中的每个元素识别为键和值
-
所以你可以edit这个问题来展示你如何
open文件并遍历这些行,并标记你被卡住的地方。提示:split()
标签: python python-3.x string dictionary