【问题标题】:Range object does not support assignment [duplicate]范围对象不支持赋值[重复]
【发布时间】:2019-07-17 14:59:06
【问题描述】:

我不断收到 TypeError 'Range' 对象不支持项目分配。我尝试稍微更改代码,例如在范围之前添加 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 是第二个函数的给定参数,它表示 iter(range(len(graph))) 中的 node。我用 iter 和 list 试过了,都不管用。怎么办?

【问题讨论】:

  • 这么长时间后关闭,建议的欺骗目标是 100% 相同的......叹息

标签: python python-3.x


【解决方案1】:

anchors = range(len(graph)) 在 python 2 中生成一个list,以便您可以分配给它。

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

来自documentation

range不是一个函数,实际上是一个不可变的序列类型

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

快速修复:在range 对象上强制迭代,您将获得一个可以使用切片赋值的对象:

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

【讨论】:

  • 哇,太棒了,谢谢!我一直在尝试使用“节点”,我认为错误是因为 start = node。
  • 是的,for node in iter(range(len(graph))): iter 在这里没用。
  • 啊! Nitpick,但它确实成为生成器函数。它是一个不可变的、常量内存的序列类型,支持延迟生成它的值。它不是发电机。它甚至不是一个迭代器。如果你不相信我,试试r = range(10); next(r)
  • “范围对象”是明确的术语。同样,这只是一个挑剔,并不会真正影响您的答案。
  • 好吧,但调用 range 一个“范围对象”对我来说似乎是一个循环定义:)
猜你喜欢
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2022-01-12
  • 1970-01-01
  • 2017-09-01
  • 2016-09-29
相关资源
最近更新 更多