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

Time:12-07

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?

CodePudding user response:

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)]

CodePudding user response:

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

  • Related