范围对象不支持赋值

2024-10-01 09:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直得到一个TypeError'Range'对象不支持项分配。我试着稍微修改一下代码,比如在range之前添加iter(…),以及list(…)before range。但是,这没有帮助,错误还在继续。 代码如下:

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是来自第二个函数的给定参数,它在iter中表示for node(range(len(graph)))。我用iter和list试过了,都没用。怎么办?在


Tags: innodea2forlabelslenifa1
1条回答
网友
1楼 · 发布于 2024-10-01 09:29:42

anchors = range(len(graph))在python2中生成一个list,这样您就可以为它赋值了。在

但是在python3中,这种行为已经改变了。range成为一个延迟序列生成对象,这节省了内存和CPU时间,因为它主要用于循环计数,并且很少使用它生成连续的实际list。在

来自documentation

Rather than being a function, range is actually an immutable sequence type

而且这样的对象不支持片分配([]操作)

Quickfix:在range对象上强制迭代,您将得到一个可以使用切片分配的对象:

anchors = list(range(len(graph)))

相关问题 更多 >