Reputation: 785
I had a txt file which contained info regarding SAT scores by each state. I created 3 empty list and appended using following code. Now, I would like to subset the list such that output display statenames with verbal score >20. Below is my example of the dataset:
filepath=open('myfile.txt','r')
l=[]
states=[]
verbals=[]
maths=[]
for h in filepath:
n=h.strip()
b=n.split()
l.append(b)
for (state,verbal,math) in l:
states.append(state)
verbals.append(verbal)
maths.append(math)
filepath.close()
State Verbal Math
NY 50 100
NJ 10 90
DC 25 50
Carolina 40 10
I tried below code but got error
Verbal[verbal>20]
**Error:**'>' not supported between instances of 'list' and 'int'
Being a newbie to python if you could provide the explanation with code that will be great!
Upvotes: 0
Views: 48
Reputation: 960
state = ['NY','NJ','DC','Carolina']
verbal = [50,10,25,40]
math = [100,90,50,10]
for idx, _ in enumerate(verbal):
if verbal[idx] > 20:
print("State {0}: Verbal {1}: Math {2}".format(state[idx], verbal[idx], math[idx]))
or using Tuples:
satScore = [('NY', 50, 100), ('NJ', 10, 90), ('DC', 25, 50), ('Carolina', 40, 10)]
for idx, _ in enumerate(satScore):
if satScore[idx][1] > 20:
print("State {0}: Verbal {1}: Math {2}".format(satScore[idx][0], satScore[idx][1], satScore[idx][2]))
Output:
State NY: Verbal 50: Math 100
State DC: Verbal 25: Math 50
State Carolina: Verbal 40: Math 10
Upvotes: 1
Reputation: 5434
You are getting an error because list do not support selecting data in that manner.
You can use list comprehension to select only the scores according to what you want, which is pretty similar to the concept you have but is applied to each item in the list and returns only those that match.
Verbal_above20 = [i for i in verbals if i > 20]
But because of the way you store your data, it will be difficult to get the other parts of your data corresponding to a key. I highly suggest you check out pandas for work regarding cleaning and munging data.
Upvotes: 0