【发布时间】:2017-10-29 07:21:54
【问题描述】:
这是我在 StackOverflow 上的第一个问题,我搜索了很多网站,但找不到我想要的(或没有注意到)。请不要气馁:)
另外,这是我第一次使用 Python 编程,我很困惑。
我有一个文本文件,里面有 3 列,用 WhiteSpaces 分隔。这些列是DeptID、CourseID、NumberofStudentsEnrolled。
这里是示例数据:
101 10001 23
102 10002 30
102 10004 5
102 10005 13
105 10006 59
105 10007 77
所以,每当我调用DeptID 索引和CourseID 索引时,程序都会给我注册的学生人数。
例如:NumberofEnrolled("101","10001") 应该给出23 作为答案。
我应该改用矩阵吗?因为我有点迷路了。我知道我想要什么,但我不知道它在Python 中叫什么。
import numpy
depts = []
courses = []
file = open("C:\\Info.txt", "r")
# SPLIT EVERY LINE INTO 3 PIECES : DeptID , CourseID , Enrolled
for line in file:
depts.append(line.split()[0]) # ADD Depts
courses.append(line.split()[1]) # ADD Courses
# CLOSE THE FILE
file.close()
# I HAVE TRIED NUMPY BUT COULDN'T HANDLE WITH IT.
numpyList = numpy.zeros((57, 57), dtype = numpy.int32)
dept_array = numpy.array(dept)
course_array = numpy.array(course)
test_dict = {}
for i in range(len(dept_array)):
test_dict[dept_array[i]] = course_array[i]
test_dict 输出为:
{'101': '10001', '102': '10005', '105': '10007'}
此输出仅获取多个数据的最后一个数据。我想我需要一种可以在里面容纳多对的类型。
【问题讨论】:
-
我建议查看
dataframes和pandas -
我不能用 numpy 做这个吗?
-
这可以通过字典轻松完成,您不一定需要重量级(
numpy或pandas)解决方案
标签: python dictionary indexing