在python中一次比较两个数据库记录

时间:2016-10-27 10:29:08

标签: python list

我试图比较数据库表中的学生对。 我的数据库表如下:

    id | edu
    1  | 1
    2  | 1
    3  | 2
    4  | 2

我一次比较一对学生,如果他们有相似的教育代码,我将他们输入到一个列表,其ID为1,如果不是0。 我的代码如下:

    #getting edu info
    data=curr.execute('select id,edu from student_details')
    result = curr.fetchall()
    mydic1=dict(result)

    data2=curr.execute('select id,edu from student_details ')
    result2 = curr.fetchall()
    mydic2=dict(result2)

    looping=curr.execute('select count(id) from student_details where id <= 4')
    loop_times = curr.fetchall()
    count = int(loop_times[0][0])

    count = count + 1
    listOflist=[]
    x=0
    for i in range(1,count):
        row = [] 
        for x in range(0,i):
            row.append(0)
        for j in range(i+1, count):
            if mydic1[i]==mydic2[j]:
               row.append(1)
            else:
               row.append(0)
        listOflist.append(row)
      print edu

这将按照我想要的方式打印输出,如下所示:

     [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0]]

但我不知道这是否是比较python中数据库记录的最有效方法。欢迎任何改进建议。

1 个答案:

答案 0 :(得分:0)

一种方法是使用defaultdict并创建一个字典,其中包含每个“edu”号码的学生编号列表。所以结果与此类似:

edu_map == {1: [1, 2], 2: [3, 4]}

基本思想是你遍历表格中的每个条目,并将学生的号码添加到结果字典中的“edu”号码中:

edu_map = defaultdict(list)
for stud, edu in mydic1.items():
    edu_map[edu] += [stud]

defaultdict的原因是它在被请求时自动创建一个新的字典条目(在这种情况下为空列表)但不存在。因此,您无需检查if edu not in edu_map,然后添加一个空列表,因为defaultdict会为您执行此操作。

要将此结果转换为与您类似的列表,您可以再次浏览每个学生并获取他们的“edu”号码,然后使用edu_map中的数字来获取该列表:

result = []
for stud, edu in mydic1.items():
    stud_in_edu = edu_map[edu]
    stud_in_edu = [1 if other_stud != stud and other_stud in stud_in_edu else 0
                   for other_stud in range(len(mydic1))]
    result.append(stud_in_edu)

这假定mydic1仅包含有效条目。如果您已经拥有所有条目,则无需在单独的SQL查询中另外计算它们。