Reputation: 18181
I am trying to sort a list in python by one of it's property, however, it's not sorted correctly, any hint.
I try to print the value before and after sort, they are printing the same value.
def kmeans_clustering(cluster_list, num_clusters, num_iterations):
"""
Compute the k-means clustering of a set of clusters
Input: List of clusters, number of clusters, number of iterations
Output: List of clusters whose length is num_clusters
"""
# initialize k-means clusters to be initial clusters with largest populations
for idx in range(len(cluster_list)):
print cluster_list[idx].total_population()
print "sort.."
sorted(cluster_list, key = lambda x: x.total_population(), reverse = True)
for idx in range(len(cluster_list)):
print cluster_list[idx].total_population()
Upvotes: 0
Views: 129
Reputation: 369444
sorted
returns a new sorted list, and does not sort the list in-place.
>>> x = [3, 2, 1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]
If you want to sort in-place, use list.sort
instead:
>>> x.sort()
>>> x
[1, 2, 3]
Side note:
Instead of using the index to access each element, just iterate the list:
for cluster in cluster_list:
print cluster.total_population()
Upvotes: 5