Python 类型错误:“范围”对象不支持项目分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20484195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:34:32  来源:igfitidea点击:

TypeError: 'range' object does not support item assignment

pythonpython-3.x

提问by user2840982

I was looking at some python 2.xcode and attempted to translate it to py 3.xbut I'm stuck on this section. Could anyone clarify what is wrong?

我正在查看一些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)

This was the error given:

这是给出的错误:

TypeError: 'range' object does not support item assignment

采纳答案by Tim

In Python 3, rangereturns a lazy sequence object - it does not return a list. There is no way to rearrange elements in a range object, so it cannot be shuffled.

在 Python 3 中,range返回一个惰性序列对象——它不返回一个列表。无法重新排列 range 对象中的元素,因此无法对其进行洗牌。

Convert it to a list before shuffling.

在洗牌之前将其转换为列表。

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