Reputation: 23
I'm quite new and still learning python. I need to know how to compare items in a list to another list.
mc_zip = zip(name, class)
mc_list = list(mc_zip)
class_zip = zip(class_name, class_number)
class_list = list(class_zip)
print(mc_list)
print(class_list)
output
mc_list = [('AA', 5537), ('AA', 5620), ...., ('AB', 5531)]
class_list = [('AA', 5537), ('AA', 1244), ...., ('AZ', 4545)]
mc_list
is the students that did not attend class while the class_list
is the list of students at the school. I would like to know how can I compare the names of the mc_list
to the class_list
and after that be able to pluck out the data from the mc_list
that has the same name. So that I can know the classes that particular name took.
The new output should be:
mcstudentclass = [('AA', 5537),('AA', 5540), ('AA', 1244),('AB', 5531), ('AB', 6636),.....]
If you are wondering where ('AB', 6636) or ('AA', 5540) come from. It came from class_list the .... (....)represents over a few repeating names that have different class numbers and vice versa. Sorry if it is a bit hard to understand.
Upvotes: 0
Views: 92
Reputation: 38
Place the class list in a dictionary. The compare the mc_list to it. It will save a lot of time.
If compare a list against a list it has to traverse the list. I dictionary look up doesn't require that.
Upvotes: 0
Reputation: 5264
If you need the list of classes that people attended from the list of classes they are registered for and the list of classes they missed, here are two options, which start with the same zipped format you provided.
names = ["Alice", "Bob", "Charlie"]
classes = [1, 2, 3]
registered = [("Alice", 1), ("Alice", 2), ("Alice", 3), ("Bob", 2), ("Bob", 3), ("Charlie", 1), ("Charlie", 3)]
missed = [("Alice", 1), ("Charlie", 3)]
# 1. list comprehension
attended = [p for p in registered if p not in missed]
print(attended)
# 2. set difference
attended = set(registered) - set(missed)
print(attended)
Upvotes: 1