Strange error with range type in list assignment

不打扰是莪最后的温柔 提交于 2019-12-10 13:44:34

问题


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] = []

The traceback I am getting a strange error:

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

Not sure why it is throwing this exception, did they change something in Python 3.2?


回答1:


Good guess: they did change something. Range used to return a list, and now it returns an iterable range object, very much like the old xrange.

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

You can get an individual element but not assign to it, because it's not a list:

>>> 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

You can simply call list on the range object to get what you're used to:

>>> 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]



回答2:


Try this for a fix (I'm not an expert on python 3.0 - just speculating at this point)

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


来源:https://stackoverflow.com/questions/9091044/strange-error-with-range-type-in-list-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!