c) A function named tallied_data() that takes in a nested list (Use this on the data from part 1, but it should be able to be used to solve similar problems), indices for two columns and returns a tallied list.
The inputs are: i) a nested list,
ii) an index for the ‘reference column’/ ‘category’ (col_ref)
iii) another index for the column to be tallied (col_tally)
iv) this function returns a list of tuples where each element is a tuple with two elements, the first one is the reference/category and the second one is the tallied sum for all the rows that have the reference. This list will be returned sorted in descending order based on the tallied numbers. (hint: see Lesson 19)
For example using the tallied_data() function from part c: data = [[Indiana, 2, 'Clinton', 4], [‘Colorado’, 2, ‘Bush’, 56], [‘Colorado’, 2, 'Clinton', 100], [‘Illinois’, 3, ‘Gore’, 8], [Oregon, 3, 'Clinton', 4], [Indiana, 4, ‘Bush’, 2]] print(tallied_data(data, 2, 3)) will display [('Clinton', 108), ('Bush', 58), ('Gore', 8)] print(tallied_data(data, 0, 3)) will display [(‘Colorado’, 156), (‘Illinois’, 8), (‘Indiana’, 6), (‘Oregon’, 4)]
def tallied_data(data,ref,col):
tally={}
for i in data:
if i[ref] in tally:
tally[i[ref]]+=i[col]
else:
tally[i[ref]]=i[col]
tups = []
for i in tally:
tups.append((i,tally[i]))
return sorted(tups,reverse=True,key = lambda x: x[1])
Get Answers For Free
Most questions answered within 1 hours.