Skip to main content
 首页 » 编程设计

python之Range对象不支持赋值

2025年05月04日15Free-Thinker

<分区>

我不断收到 TypeError 'Range' object does not support item assignment。我尝试稍微更改代码,如在范围之前添加 iter(...) 以及在范围之前添加 list(...) 。但是,它没有帮助,错误仍在继续。 这是代码:

def findAnchor(anchors, node): 
    start = node                    
    while node != anchors[node]:    
        node = anchors[node]        
    anchors[start] = node           
    return node 
 
def unionFindConnectedComponents(graph): 
    anchors = range(len(graph))         
    for node in iter(range(len(graph))):     
        for neighbor in graph[node]:    
            if neighbor < node:         
                continue 
 
            a1 = findAnchor(anchors, node)        
            a2 = findAnchor(anchors, neighbor)    
            if a1 < a2:                           
                anchors[a2] = a1                  
            elif a2 < a1:                         
                anchors[a1] = a2                  
 
    labels = [None]*len(graph)          
    current_label = 0                   
    for node in range(len(graph)): 
        a = findAnchor(anchors, node)   
        if a == node:                   
            labels[a] = current_label   
            current_label += 1          
        else: 
            labels[node] = labels[a]    
 
 
    return anchors, labels 

现在 TypeError 出现在 anchors[start] = node. node 是第二个函数的给定参数,它表示 for node in iter(range(len(graph)))。我用 iter 和 list 试过了,都没有用。怎么办?