Python排序不正常

时间:2014-10-04 05:20:13

标签: python list python-2.7

我试图通过其中一个属性在python中对列表进行排序,但是,它没有正确排序,任何提示。

我尝试在排序前后打印值,它们打印相同的值。

 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()

1 个答案:

答案 0 :(得分:5)

sorted返回一个新的排序列表,并不会就该列表进行排序。

>>> x = [3, 2, 1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

如果您想就地排序,请改用list.sort

>>> x.sort()
>>> x
[1, 2, 3]

旁注:

不是使用索引来访问每个元素,只需迭代列表:

for cluster in cluster_list:
    print cluster.total_population()