'How can I find the state with the best average
I have a made a list from a JSON file like this:
['1', 'California', '67'], ['2', 'Arizona', '63'], ['3', 'New York', '78'], ['4', 'New York', '78'], ['5', 'Ohio', '65'], ['6', 'Israel', '69'], ['7', 'North Carolina', '96'], ['8', 'Kansas', '87'], ['9', 'Canada', '91'], ['10', 'New York', '71'], ['11', 'Mississippi', '82'], ['12', 'Virginia', '79'], ['13', 'Bulgaria', '79'], ['14', 'Russia', '70'], ['15', 'New York', '82'], ['16', 'Utah', '80'], ['17', 'Holland', '75'], ['18', 'Mexico', '95'], ['19', 'Venezuela', '92'], ['20', 'Puerto Rico', '95'], ['21', 'Oregon', '67'], ['22', 'New York', '82'], ['23', 'Massachusetts ', '89'], ['24', 'China', '79'], ['25', 'Sweden', '88'], ['26', 'Minnesota', '96'], ['27', 'Pennsylvania', '88'], ['28', 'Oklahoma', '64'], ['29', 'Argentina', '85'], ['30', 'Louisiana', '79']]
The first element of each list represents the ID of the applicant. The second element represents the State and the third one represents the Scores.
I have tried this code so far but it is not working properly:
***m=0
b=0
for state in a:
if state=='New York':
m+=state.grade
b+=1
print(f'New York's average score is {m/b}')***
It brings me out: New York's average score is 0. Each time.
I tried to make the code for one state, so that I can do it to solve the whole problem.
Solution 1:[1]
If I understand you correctly, you want to find best average among the states you have (lst is your list from question):
states = {}
for _, state, score in lst:
states.setdefault(state, []).append(int(score))
lowest = min(states, key=lambda s: sum(states[s]) / len(states[s]))
print(lowest)
Prints:
Arizona
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
