python - Range对象不支持赋值

标签 python python-3.x

<分区>

我不断收到 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 试过了,都没有用。怎么办?

最佳答案

anchors = range(len(graph)) 在 python 2 中生成一个 list,因此您可以对其进行分配。

但在 python 3 中,行为发生了变化。 range 成为惰性序列生成对象,节省了内存和 CPU 时间,因为它主要用于循环计数,很少用于生成连续的实际 list

来自 documentation :

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

并且此类对象不支持切片赋值([]操作)

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

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

关于python - Range对象不支持赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44833600/

相关文章:

Python 具有条件的数据帧的聚合总和

python - 访问对象数据切片 numpy 数组

python多处理/线程代码提前退出

python - boto3 codecommit create_commit问题

python - 通过 importlib 以编程方式导入模块 - __path__ 未设置?

python - 如何在 put_object 中指定标记?

python - 正确安排两个for循环的结果

Python-将 channel 添加到类别

python - 将数组的值分配给另一个数组的最 Pythonic 方式

python - 如何在不聚合原始 RDD 分区的情况下对多个 RDD 进行分组?