【问题标题】:Python : Can Dictionary be used for indexing?Python:字典可以用于索引吗?
【发布时间】:2017-10-29 07:21:54
【问题描述】:

这是我在 StackOverflow 上的第一个问题,我搜索了很多网站,但找不到我想要的(或没有注意到)。请不要气馁:)

另外,这是我第一次使用 Python 编程,我很困惑。

我有一个文本文件,里面有 3 列,用 WhiteSpaces 分隔。这些列是DeptIDCourseIDNumberofStudentsEnrolled

这里是示例数据:

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'}

此输出仅获取多个数据的最后一个数据。我想我需要一种可以在里面容纳多对的类型。

【问题讨论】:

  • 我建议查看 dataframespandas
  • 我不能用 numpy 做这个吗?
  • 这可以通过字典轻松完成,您不一定需要重量级(numpypandas)解决方案

标签: python dictionary indexing


【解决方案1】:

您可以轻松地将数据读入字典字典:

data = {}
for line in file:
    dept, course, num_students = line.split()
    data.setdefault(dept, {})[course] = int(num_students)

现在您可以查找了:

>>> data["101"]["10001"]
23

【讨论】:

    【解决方案2】:

    其他人给了你一些选择。

    我会提议,因为 (deptID, courseID) 对是唯一的,您可以使用元组作为密钥。

    depts = dict()
    
    depts[(101,10001)] = 23
    depts[(102,10002)] = 30
    depts[(102,10004)] = 5
    depts[(102,10005)] = 13
    depts[(105,10006)] = 59
    depts[(105,10007)] = 77
    
    
    print(depts)
    #output: {(102, 10002): 30, (101, 10001): 23, (105, 10006): 59, (102, 10005): 13, (105, 10007): 77, (102, 10004): 5}
    
    print(depts.keys())
    #output: [(102, 10002), (101, 10001), (105, 10006), (102, 10005), (105, 10007), (102, 10004)]
    
    #should you ever need to access all the courses associated with an ID you 
    #can use a filter with a lambda or more easily a List Comprehension
    #to identify that data.  But this will be have O(n) time look up as opposed
    #to a dictionary of dictionaries which would have a O(1) look up for 
    #associated courseID lookups.
    print([catalogue[1] for catalogue in depts.keys() if catalogue[0] == 102])
    #output: [10002, 10005, 10004]
    
    
    for (i,j) in depts.keys() :
        print (depts[(i,j)])
    #output:   30
    #output:   23
    #output:   59
    #output:   13
    #output:   77
    #output:   5
    

    【讨论】:

    • 对不起,我是 Phyton 的新手 :) 所以我可以做类似depts[(i, j)]
    • 没有什么可以为 bud 道歉的。如果您希望将来更多地使用 python,您可能需要获取 Oreilly 的 python 食谱的副本。它帮助了很多人,我认为这是一本相当不错的读物。
    • 谢谢@FredMan。我可以做类似 depts[(i, j)] 的事情吗?
    • 当然。将 i 设置为某个变量,将 j 设置为某个变量,然后调用 depts[(i,j)] 它会找到学生人数。我将编辑我的帖子以提供示例。
    • 非常感谢。这很有帮助:)
    【解决方案3】:

    如果您将数据转换为字典会很容易。

    打开您的 info.txt 文件并另存为 info.csv。这样做的原因是,因为 csv 可以轻松处理空格或逗号以及任何其他分隔符。

    import csv
    
    data_dict = {}
    # you can change the delimiter if its something other than space.
    with open("C:\\Info.txt", "r") as fobj:
        data = csv.reader(fobj, delimiter=' ')
    
        # reading the rows/lines of the file
        for row in data:
            if row[0] in data_dict.keys():
                data_dict[row[0]][row[1]] = row[2]
            else:
                data_dict[row[0]] = {row[1]: row[2]}
    
    def func(dept_id, course_id):
        # check whether the dept_id exists in your current dictonary
        if dept_id in data_dict.keys():
            # check whether the course_id exists in your current dictonary
            if course_id in data_dict[dept_id].keys():
                return data_dict[dept_id][course_id]
            else:
                print ('Invalid course id')
        else:
            print ('invalid department id')
    
    print func('101', '10001')
    

    【讨论】:

    • 当前错误,data_dict[row[0]] = {row[1]: row[2]} 将继续覆盖与row[0] 关联的值,而不是向其添加新数据。
    • @donkopotamus 感谢您指出这一点。我现在已经更正了。
    【解决方案4】:

    如果您真的想同时使用 DeptID 和 CourseID,您似乎需要一个二维查找表(不是实际的 Python 内置的东西),首先查找 DeptID(在字典中)可能会给您一个表(字典)与对应于该部门的注册编号配对的 Co​​urseID。

    效率有点低,但在我看来,所有 CourseID 都将是唯一的,如果是这样,您是否可以仅基于此进行查找?

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2016-07-11
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多