I am using colab. I have a list with these values:
cents=[[5.4, 3.9, 1.3, 0.4], [5.8, 2.6, 4.0, 1.2], [7.7, 2.8, 6.7, 2.0]]
I established this list in my second block of code.
Now, further into my code, I want to clear this list and change the values to the average of values from another list. Here is my code for this:
cents=[]
def avg_and_assign(list_1, list_2, list_3):
alc1=np.array(list_1)
alc2=np.array(list_2)
alc3=np.array(list_3)
alc1_mean=np.mean(alc1, axis=0)
alc2_mean=np.mean(alc2, axis=0)
alc3_mean=np.mean(alc3, axis=0)
alc1_mean1=alc1_mean[0:4]
alc2_mean1=alc2_mean[0:4]
alc3_mean1=alc3_mean[0:4]
cent1=np.ndarray.tolist(alc1_mean1)
cent2=np.ndarray.tolist(alc2_mean1)
cent3=np.ndarray.tolist(alc3_mean1)
cents.append(cent1)
cents.append(cent2)
cents.append(cent3)
cents=[cent1,cent2,cent3]
cent_array=np.array(cents)
print(cents)
avg_and_assign(avg_list_cent1, avg_list_cent2, avg_list_cent3)
print(cents)
Here are my outputs:
[[5.4, 3.9, 1.3, 0.4], [5.8, 2.6, 4.0, 1.2], [7.7, 2.8, 6.7, 2.0]]
[[5.4, 3.9, 1.3, 0.4], [5.8, 2.6, 4.0, 1.2], [7.7, 2.8, 6.7, 2.0], [5.005999999999999, 3.4180000000000006, 1.464, 0.2439999999999999], [5.971830985915493, 2.7845070422535207, 4.50281690140845, 1.4901408450704228], [6.972413793103449, 3.0862068965517238, 5.893103448275861, 2.1310344827586207]]
Why isn't my cents list becoming empty when I assign it empty? Can this only work in the same code block?
My function can append the average to the list, but I wanted cents to become a blank list first.
Thanks.
CodePudding user response:
Don't Repeat Yourself ("DRY"). Use a loop to do your repetitive tasks. Then, return the final list instead of trying to use globals.
def avg_and_assign(*lists):
cents = []
for lst in lists:
alc = np.array(lst)
alc_mean = np.mean(alc, axis=0)[:4]
cents.append( np.ndarray.tolist(alc_mean) )
return cents
cents=[cent1,cent2,cent3]
print(cents)
cents = avg_and_assign(avg_list_cent1, avg_list_cent2, avg_list_cent3)
print(cents)
It's not clear to me why you keep converting to and from numpy arrays. In particular, why return a list of lists instead of a list of ndarrays?