How can I perform this calculation on each [nth] item and append it to a list of lists in python?

Question:

For example, the following list has x number of items each (2 in the one below, item1 and item2 in each sublist).

alist = [[1,2],[4,1],[3,2]…]

I want to get the average of item1 and the average of item2 throughout all sublists.

Output should be something like: [(‘item1’, item1’s avg), (‘item2’, item2’s avg), … ]

I’m having trouble finding out how I can do this with 2 unknowns, the number of items, and the number of sublists. Is there a pythonic way to do this?

Asked By: micheal cay

||

Answers:

I’m not sure I understood you correctly, is this what you were asking?

alist = [[1,2],[4,1],[3,2]] 
print([(l, sum(l)/len(l)) for l in alist])

Output:

[([1, 2], 1.5), ([4, 1], 2.5), ([3, 2], 2.5)]
Answered By: Joan Lara Ganau

averages = [sum(sublist)/len(sublist) for sublist in alist]

Answered By: supersquires
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.