문제

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?

도움이 되었습니까?

해결책

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]

다른 팁

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)]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top