Reputation: 73
so this question is quite complicated to explain. Say I have a list of list of list of grades and a name, for example:
a=[[90,50,40],'Josh']
b=[[85,60,90],'Becky']
c=[a,b]
so that c would be:
c=[[[90,50,40],'Josh'],[[85,60,90],'Becky']]
now let's say the list is much longer and I'm interested in a student who got a list of grades of [100,100,100]. How can I loop over that?
From my usage of MATLAB I know I used c[:][0] to get a "list" of the grades.
Now I'd like to do something as:
target=[100,100,100]
if target in c[:][0]:
print 'we got a smart fella in the hood'
how can I do that in python? Thanks a lot!
Upvotes: 0
Views: 733
Reputation: 191738
I would recommend going a class-based approach to get away from nested lists
class Student():
def __init__(self, name, scores):
self.name = name
self.scores = scores
def has_perfect_scores():
return all(score == 100 for score in self.scores)
Then,
c = [ Student('Josh', [90,50,40]), Student('Becky', [85,60,90]) ]
for student in c:
if student.has_perfect_scores():
print 'we got a smart fella in the hood named {}'.format(student.name)
For any student you can loop over their scores
list
Upvotes: 0
Reputation: 65
If you need only to know if there is a match, you can do:
c=[[[90,50,40],'Josh'],[[85,60,90],'Becky']]
target = [85,60,90]
if target in [i[0] for i in c]:
print "true"
Upvotes: 0
Reputation: 77857
According to your code, the matrix c would appear as a nested list structure. Digging down the levels ...
c[1] is [[85,60,90],'Becky']
c[1][0] is [85,60,90]
c[1][0][2] is 60
That should explain the naming to you. Now, you need to check the scores lists, c[*][0] for the target values. If you need an exact match, it's easy enough: build a temporary list of the values and report if there's a hit.
if target in [record[0] for record in c]:
print "Smart person exists"
If you need to print a list of the names, try
print [record[1] for record in c if record[0] == target]
Does that get you moving?
Upvotes: 0
Reputation: 48077
You should be iterating like:
c = [[[90,50,40],'Josh'],[[85,60,90],'Becky'], [[100,100,100],'Mano']]
target = [100,100,100]
for grade, name in c:
if grade == target:
print name
which will print:
Mano
If you want the list of all the name satisfying the mentioned criterion, you may use a list comprehension expression as:
names = [name for grade, name in c if grade == target]
Upvotes: 4