python如何赋值范围_范围对象不支持赋值

该博客讨论了一个在Python代码中遇到的TypeError,具体为'Range'对象不支持项分配。作者尝试了使用iter()和list()来解决,但问题依然存在。代码涉及了并查集(Union-Find)算法,用于查找图中的连通分量。错误出现在将节点赋值给anchors数组时。尽管提供了详细代码,但解决方案尚未找到。博客寻求关于如何解决此特定TypeError的建议。
摘要由CSDN通过智能技术生成

我一直得到一个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试过了,都没用。怎么办?在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值