Htet
Htet

Reputation: 159

Find the mean value in a list, and return the results score over mean value in Python

A given list contains 3 elements for each record as below:

a_list = [('This is A.', 00, 2.0),
          ('This is B.', 01, 3.0),
          ('This is C.', 02, 3.0),
          ('This is D.', 03, 1.5)]

The result should produce only the records with the scores which equal or more than average value in third elements. The result should be like this:

result = [('This is B.', 01, 3.0),
          ('This is C.', 02, 3.0)]

Because the mean of third element in given list is 2.375. This is the attempt I've been trying and the error message, see below:

get_mean = np.mean(dict(a_list).values())
d = dict(a_list)
get_final = dict((x, y, z) for x, y, z in d.items() if z >= get_mean)
get_item = get_final.items()
get_result = sorted(get_item, reverse=True, key=lambda tup: tup[1])

return get_result


ErrorMsg --> ValueError: dictionary update sequence element #0 has length 3; 2 is required

Upvotes: 1

Views: 74

Answers (2)

Miriam Farber
Miriam Farber

Reputation: 19634

This will do the job:

a_list = [('This is A.', '00', 2.0),
          ('This is B.', '01', 3.0),
          ('This is C.', '02', 3.0),
          ('This is D.', '03', 1.5)]
avg=float(sum(i[2] for i in a_list))/len(a_list)
res=[i for i in a_list if i[2]>=avg]

Upvotes: 2

Carles Mitjans
Carles Mitjans

Reputation: 4866

You can try using list comprehensions:

mean = sum(x[2] for x in a_list)/len(a_list)
[x for x in a_list if x[2] >= mean]

Output:

[('This is B.', 1, 3.0), 
 ('This is C.', 2, 3.0)]

Edit:

The error you are getting comes from dict(a_list). When creating a dictionary from a list of tuples, each tuple should have 2 elements (key, value). It is not possible to create a dictionary with tuples of 3 elements.

Upvotes: 2

Related Questions