Finding mean of a part of list in python and then modifying the list

Viewed 186

I have a list like this

x = [4342, 318, 262, 6827, 314, 765, 11525, 67, 654, 13]


And I want to take mean of 11525,67 and 654, and then put it at the index of 11525. So, basically I want my list x to be like this :-

x = [4342, 318, 262, 6827, 314, 765, 4082, 13]

I know how to take the average but do not know about how can I modify the list by deleting the indices. This is what I've done so far

sum = 0
count = 0
for x in range(6, 9):
  sum += text_index[x]
  count += 1
print(sum, count)
avg = int(sum/count)
print(avg)

Now, how should I edit my list to get the desired output?

5 Answers

You can use list slicing and then reassemble the list.

x = x[0:6] + [sum(x[6:9])/3, x[-1]]
targets = []
for i in range(6,9):
    targets.append(text_index.pop(i))  # use pop to remove the item and return it
sum = sum(text_index)  # Use sum() on an iterable to sum each item
avg = sum/len(targets)  # Calculate the mean using the len

You can do it with list slices and concatenation. For example:

text_index = [4342, 318, 262, 6827, 314, 765, 11525, 67, 654, 13]

sum = 0
count = 0
start, stop = 6, 9
for x in range(start, stop):
  sum += text_index[x]
  count += 1
print(sum, count)
avg = int(sum/count)
text_index = text_index[:start] + [avg] + text_index[stop:]
print(text_index)

Simple way, try this:

import numpy as np
x = [4342, 318, 262, 6827, 314, 765, 11525, 67, 654, 13]
y = x[6:9]
del(x[6:9])
av = np.mean(y)
x.insert(len(x)-1, int(av))
print(x)

output:

[4342, 318, 262, 6827, 314, 765, 4082, 13]

You could simply use del x[7:9]. Here is a simple function that probably does what you need:

def replace_by_mean(x):
    avg = sum(x[6:9]) // len(x[6:9])
    x[6] = avg
    del x[7:9]
Related