TypeError:“范围”对象不支持项目分配 - python

我正在查看一些python 2.x代码,并尝试将其转换为py 3.x,但我仍停留在此部分。任何人都可以澄清出什么问题吗?

import random

emails = {
    "x": "[REDACTED]@hotmail.com",
    "x2": "[REDACTED]@hotmail.com",
    "x3": "[REDACTED]@hotmail.com"
}

people = emails.keys()

#generate a number for everyone
allocations = range(len(people))
random.shuffle(allocations)

这是给出的错误:

TypeError: 'range' object does not support item assignment

参考方案

在Python 3中,range返回一个惰性序列对象-它不返回列表。无法重新排列范围对象中的元素,因此不能重新排列它。

改组之前将其转换为列表。

allocations = list(range(len(people)))

Python TypeError:“类型”对象不支持项目分配 - python

我必须设计并实现一个TwoSum类。它应该支持以下操作:add-将数字添加到内部数据结构中。find-查找是否存在任何一对数字,其总和等于该值。这是我的代码:class TwoSum(object): dict = {} def add(self,n): dict[n] = n #TypeError: 'type' object does…

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

TypeError:_transform()接受2个位置参数,但给出了3个 - python

我了解了CaesarCipher:In [90]: !cat caesar_cipher.py class CaesarCipher: """Construct Caesar cipher using given integer shift for rotation.""" def __init__…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

写入日志文件时出现TypeError - python

我使用以下代码设置了一个记录器:logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='application.log', mode='a+') handler…