원하는 것을 간단하게하기 위해 데이터 멤버 및 메서드를 사용하여 클래스를 유지 관리하고 유지 관리하는 간단한 클래스를 만들 수 있습니다. 이 문제에 대해 두 개의 사전이 필요할 것입니다. 학생 이름 (또는 ID)을 입력하여 각각의 과목을 추적하고, 다른 하나는 각 반마다 어떤 학생이 있는지 추적합니다.
defaultdicts
'collections'모듈에서 일반 dicts
대신 사용할 수 있습니다. 여기의 의미는 다음과 같습니다
실행은 다음과 같은 출력을 생성
from collections import defaultdict
class Enrollment(object):
def __init__(self):
self.students = defaultdict(set)
self.courses = defaultdict(set)
def clear(self):
self.students.clear()
self.courses.clear()
def enroll(self, student, course):
if student not in self.courses[course]:
self.students[student].add(course)
self.courses[course].add(student)
def drop(self, course, student):
if student in self.courses[course]:
self.students[student].remove(course)
self.courses[course].remove(student)
# remove student if they are not taking any other courses
if len(self.students[student]) == 0:
del self.students[student]
def display_course_enrollments(self):
print "Class Enrollments:"
for course in self.courses:
print ' course:', course,
print ' ', [student for student in self.courses[course]]
def display_student_enrollments(self):
print "Student Enrollments:"
for student in self.students:
print ' student', student,
print ' ', [course for course in self.students[student]]
if __name__=='__main__':
school = Enrollment()
school.enroll('john smith', 'biology 101')
school.enroll('mary brown', 'biology 101')
school.enroll('bob jones', 'calculus 202')
school.display_course_enrollments()
print
school.display_student_enrollments()
school.drop('biology 101', 'mary brown')
print
print 'After mary brown drops biology 101:'
print
school.display_course_enrollments()
print
school.display_student_enrollments()
:
Class Enrollments:
course: calculus 202 ['bob jones']
course: biology 101 ['mary brown', 'john smith']
Student Enrollments:
student bob jones ['calculus 202']
student mary brown ['biology 101']
student john smith ['biology 101']
After mary brown drops biology 101:
Class Enrollments:
course: calculus 202 ['bob jones']
course: biology 101 ['john smith']
Student Enrollments:
student bob jones ['calculus 202']
student john smith ['biology 101']
파이썬과 함께 패키지 된 sqlite3을 사용하는 것은 어떻습니까? 텍스트 파일을 사용하며 외부 라이브러리가 필요하지 않습니까? – GWW
[Multimap] (http://en.wikipedia.org/wiki/Multimap)이라는 용어가 유용 할 것 같습니다. 일반적으로 단방향 인덱싱에만 사용됩니다. (또한 SQLite는 최고입니다 - SQL DDL/DQL은 SQL의 모든 한계에도 불구하고 여러 가지 관계형 질문을 간단하게 만들 수 있습니다.) –