Python 3.2奇怪的错误,列表中的范围类型

时间:2012-02-01 05:02:06

标签: python python-3.2

r = range(10) 

for j in range(maxj):
    # get ith number from r...       
    i = randint(1,m)
    n = r[i]
    # remove it from r...
    r[i:i+1] = []

追溯我收到一个奇怪的错误:

r[i:i+1] = []
TypeError: 'range' object does not support item assignment

不确定为什么会抛出这个异常,他们是否在Python 3.2中改变了什么?

2 个答案:

答案 0 :(得分:6)

好猜测:他们做了改变了一些事情。用于返回列表的范围,现在它返回一个可迭代范围对象,非常类似于旧的xrange。

>>> range(10)
range(0, 10)

您可以获取单个元素但不分配给它,因为它不是列表:

>>> range(10)[5]
5
>>> r = range(10)
>>> r[:3] = []
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    r[:3] = []
TypeError: 'range' object does not support item assignment

您只需在范围对象上调用list即可获得您习惯的内容:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r = list(range(10))
>>> r[:3] = [2,3,4]
>>> r
[2, 3, 4, 3, 4, 5, 6, 7, 8, 9]

答案 1 :(得分:2)

尝试这个修复(我不是python 3.0的专家 - 只是在这一点上推测)

r = [i for i in range(maxj)]