需要匹配来自两个不同列的值,然后打印出相应列中的值

时间:2015-03-26 22:07:10

标签: python csv

我需要匹配两列中的值,但是从一个单独的列中输出值,该列只与原始列中的一列相对应。

以下是我尝试从中获取信息的电子表格示例:

Unique_ID, fullname, role, students_needed
1234, john doe, student, tim young
5678, steven tyler, student, john doe
9101, sarah joe, student, ashley fonz
2758, ashley fonz, student, rick rose

如果我需要弄清楚'student_needed'中的学生在'fullname'列中是什么,然后打印出那些学生的'Unique_ID',我该怎么做?

这是我到目前为止使用的代码,我使用的是另一个csv项目,但我似乎无法改变它以使其工作。它保持垂直打印,但也不打印正确的信息。

  1 # 1. Match Student full name with CAMS Students
  2 # 2. Match Match Schoology ID with CAMS Students
  3 # 3. Match instructor ID with Schoology ID
  4 # 4. create new csv file with student ID matched with instructor ID
  5 
  6 import os
  7 import csv
  8 from itertools import groupby
  9 from operator import itemgetter
 10 
 11 path = "/Users/brandon/desktop/"
 12 
 13 writers = {}
 14  
 15 with open(os.path.join(path, "Schoology_Unique_IDs.csv"), "rbU") as rosters:
 16 
 17     reader = csv.DictReader(rosters)
 18     headers = reader.fieldnames
 19     
 20     for row in reader:
 21         if not all(row): continue
 22         fullname = row['Full Name']
 23         Schoology_ID = row['Unique User ID']
 24         CAMS_Student = row['CAMS Students']
 25         Teacher = row['Teacher Name']
 26         for row in fullname:
 27             for row in CAMS_Student:
 28                 if row == row:
 29                     print row

1 个答案:

答案 0 :(得分:1)

以下是我的表现方式。读取文件一次以获取字典中的正确名称,id关系,然后再次执行以使名称与键匹配。

import csv
with open("Schoology_Unique_IDs.csv","rbU") as f1, open("Schoology_Unique_IDs.csv","rbU") as f2:
    r1 = csv.reader(f1)
    r1.next() 
    d = {r[1]:r[0] for r in r1}
    r2 = csv.reader(f2)    
    print "\n".join([d[i[3]] for i in r2 if i[3] in d])

打印:

1234
2758