繁体   English   中英

如何在 Python 中将 for 循环转换为 while 循环?

[英]How to convert for loops to while loops in Python?

我需要改变所有的一段时间。 如何为下面的代码做到这一点? 我已经评论了每个 for 块的作用。

def createClusters(k, centroids, datadict, repeats):
    for apass in range(repeats):
    print("****PASS",apass,"****")
    clusters = []                      
    for i in range(k):
       clusters.append([])             

    for akey in datadict:              #Creating empty list of distances   

       distances = []


       for clusterIndex in range(k):   #Calculating the distances between data point and centroid and placing them into the list of distances.
           dist = euclidD(datadict[akey],centroids[clusterIndex])
           distances.append(dist)       

       mindist = min(distances)         #centroids are recalculated 
       index = distances.index(mindist)   
       clusters[index].append(akey)     
       dimensions = len(datadict[1])  #Specifies the dimension of exam score which will be one.      

    for clusterIndex in range(k):      #Sum include the sum for each dimension of data point
       sums = [0]*dimensions            #Sum initialized to zero
       for akey in clusters[clusterIndex]:
           datapoints = datadict[akey]      #Each data point will have a data key in data dictionary
           for ind in range(len(datapoints)):           #Calculates sum of components continuously
               sums[ind] = sums[ind] + datapoints[ind]  
       for ind in range(len(sums)):                    #Calculates the average
           clusterLen = len(clusters[clusterIndex])
           if clusterLen != 0:                          
              sums[ind] = sums[ind]/clusterLen   

       centroids[clusterIndex] = sums  #Assigning average to centroid list at proper positions 

    for c in clusters:          
       print ("CLUSTER")        #Prints all the data of clusters after each pass
       for key in c:            
           print(datadict[key], end=" ")
       print()                     

return clusters

你到底为什么要将所有的for循环转换为while循环。
只是为了说明这有多难看,请考虑一个规范的for循环:

for i in iterable:
    ...

会变成:

it = iter(iterable)
while True:
    try:
        i = next(it)
    except StopIteration:
        break
    ...

丑陋的!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM