def averageCandidateVotes(filename, column):
data = pd.read_csv(filename)[column]
x = data.mean()
return x
def averageVotes(filename):
candidates = ['brow', 'nade', 'harr', 'hage', 'buch', 'mcre', 'phil', 'moor']
some_list = []
for cand in candidates:
some_list.append(averageCandidateVotes(filename, cand))
return some_list
I have two functions where averageCandidateVotes returns the average vote a candidate recieved. The second function averageVotes: takes a csv file and is supposed to return a list of the means for each candidate in the candidates list. The issue is i'm only seeing one value being appended to 'some_list' instead of the values for each candidate. I'm I doing something wrong in the loop?
I'm expecting something like this as an output: [344.7164179104478, 108.32835820895522, 133.92537313432837,360.67164179104475, 109.22388059701493, 120.41791044776119, 126.91044776119404] but I'm only getting [344.7164179104478].What did I do wrong for the rest of the values not to append to the list? full datasets can be found here: https://file.io/gFugYB8sOupl
CodePudding user response:
I think you need to pull your return some_list
out one indentation level. Right now, it is part of your for cand in candidates
loop, and so right after we get that candidate's average votes, we exit the function.
If you pull it out it'll run through all candidates and then exit the function.
def averageVotes(filename):
candidates = ['brow', 'nade', 'harr', 'hage', 'buch', 'mcre', 'phil', 'moor']
some_list = []
for cand in candidates:
some_list.append(averageCandidateVotes(filename, cand))
return some_list
CodePudding user response:
this is because you are returning the list at the first check, it doesn't continue to iterate and just stops at the first.
this can be solved just by decreasing the indentation level.
def averageVotes(filename):
candidates = ['brow', 'nade', 'harr', 'hage', 'buch', 'mcre', 'phil', 'moor']
some_list = []
for cand in candidates:
some_list.append(averageCandidateVotes(filename, cand))
return some_list # <- dropped indentation level
to improve you can use a list comprehension
:
def averageVotes(filename):
candidates = ['brow', 'nade', 'harr', 'hage', 'buch', 'mcre', 'phil', 'moor']
return [averageCandidateVotes(filename,candidate) for candidate in candidates]
CodePudding user response:
Your for loop stops on the first iteration because you return a value. Thus you just append the mean of the first and only value. Therefore you just get that value back. Edit to remove first sentence that was incorrect.