views:

49

answers:

3

I am trying to perform a calculation on multiple values in the value portion of a list of key:value pairs.

So I have something like:
[('apples', ['254', '234', '23', '33']), ('bananas', ['732', '28']), ('squash', ['3'])]

I'm trying to create a list of y-values that are the averages of those integers above.

What I'm trying to write is the following pseudocode
if item[1] contains 0 elements:
ys.append(item[1])
else if item[1] contains > 0 elements:
add up elements, divide by number of elements
ys.append average number

What I'm not sure how to do is how to access all of the values that might exist in each key's value set.

+2  A: 

Where pairs is your list of pairs:

averages = [float(sum(values)) / len(values) for key, values in pairs]

will give you a list of average values.

If your numbers are strings, as in your example, replace sum(values) above with sum([int(i) for i in values]).

EDIT: And if you rather want a dictionary then a list of averages:

averages = dict([(key, float(sum(values)) / len(values)) for key, values in pairs])
Håvard S
A: 
ys = []
for k, v in items:
    avg = sum(map(float, v))/len(v)
    ys.append(v)
Daniel Roseman
A: 

You can find the mean of a list by

sum(float(i) for i in lst) / len(lst)

If the elements of the list were integers, you could do

float(sum(lst)) / len(lst)

but in your example they're strings, so you have to convert them.

In this case I would actually recommend using Python's list comprehension facility to automatically create a list of the averages. If your original list of pairs is named, say, fruit_list (I know squash is not a fruit, so sue me):

averages = [[] if len(values) == 0 else sum(float(i) for i in values)/len(values) for fruit, values in fruit_list]

Although it seems a little odd, because then you'll get a list in which some elements are floating-point numbers and other elements are empty lists. Are you sure you didn't mean to use, say, 0 instead of [] when there are no values in item[1]?

David Zaslavsky