Jan 26, 2019

Python compare lists

#Comapre lists

student1_scores = [61, 73, 84, 90, 85, 45]
student2_scores = [40, 37, 45, 87, 99, 54]

#set - will change the order
print list(set(student1_scores)) #[73, 45, 84, 85, 90, 61]
print list(set(student2_scores)) #[99, 37, 40, 45, 54, 87]

#Commom elements in two lists
print list(set(student1_scores) & set(student2_scores)) #[45]

#Commom elements in two lists
print list(set(student1_scores).intersection(set(student2_scores))) #[45]

#Union of two lists
print list(set(student1_scores).union(set(student2_scores))) 
#[99, 37, 40, 73, 45, 84, 85, 54, 87, 90, 61]

#Commom elements in two lists - using list comprehension
print [i for i in student1_scores if i in student2_scores] #[45]

#compare common elements with for the same subject (same index)
student1_scores = [61, 73, 84, 90, 85, 45]
student2_scores = [40, 37, 45, 90, 99, 54]

print [i for i, j in zip(student1_scores, student2_scores) if i == j] #[90]





No comments:

Post a Comment