How can i write this code in a shorter for loop? The code is calculating the mean of x and y values at each index
cluster_list = [[(1,2),(3,4)],[(5,6),(7,8)]]
#Creating lists to calculate mean x and y values for centroids :
mean_x_0 =[]
mean_y_0 =[]
mean_x_1 =[]
mean_y_1 =[]
# mean calculation
for i in cluster_list[0]:
mean_x_0.append(i[0])
mean_cluster_x_0 = sum(mean_x_0)/len(mean_x_0)
for i in cluster_list[0]:
mean_y_0.append(i[1])
mean_cluster_y_0 = sum(mean_y_0)/len(mean_y_0)
for i in cluster_list[1]:
mean_x_1.append(i[0])
mean_cluster_x_1 = sum(mean_x_1)/len(mean_x_1)
for i in cluster_list[1]:
mean_y_1.append(i[1])
mean_cluster_y_1 = sum(mean_y_1)/len(mean_y_1)
print(mean_cluster_x_0,mean_cluster_y_0)
print(mean_cluster_x_1,mean_cluster_y_1)
CodePudding user response:
use statistics.mean
import statistics
cluster_list = [ [ (1,2),(3,4) ] , [(5,6),(7,8)] ]
# convert the x of cluster[0] to list
cluster_x_0 = [cluster_list[0][i][0] for i in range(len(cluster_list[0]))]
# convert the y of cluster[0] to list
cluster_y_0 = [cluster_list[0][i][1] for i in range(len(cluster_list[0]))]
print (statistics.mean(cluster_x_0) , statistics.mean(cluster_y_0))
CodePudding user response:
Seems like the right opportunity to learn numpy
:
import numpy as np
np.array(cluster_list)[0].mean(axis=0)
Output: array([2., 3.])
Or, as variables:
mean_cluster_x_0, mean_cluster_y_0 = np.array(cluster_list)[0].mean(axis=0)
CodePudding user response: