python 報錯TypeError: 'range' object does not support item assignment,解決方法
阿新 • • 發佈:2018-02-23
class 問題 support nts str 數列 num 方法 star
貼問題
nums = range(5)#range is a built-in function that creates a list of integers print(nums)#prints "[0,1,2,3,4]" print(nums[2:4])#Get a slice from index 2 to 4 (exclusive); prints ‘[2,3]" print(nums[2:])#Get a slice from index 2 to the end; prints "[2,3,4]" print(nums[:2])#Get a slice from the start to index 2 (exclusive); prints "[0,1]"print(nums[:])#Get a slice of the whole list ; prints "[0,1,2,3,4]" print(nums[:-1])#Slice indices can be negative; prints "[0,1,2,3]" nums[2:4] = [8,9] # Assign a new sublist to a slice print(nums)#prints "[0,1,8,9,4]"
2.報錯的原因:
嘗試使用range()
創建整數列表(導致“TypeError: ‘range’ object does not support item assignment”)有時你想要得到一個有序的整數列表,所以range() 看上去是生成此列表的不錯方式。然而,你需要記住range() 返回的是“range object”,而不是實際的list 值。
3.解決方法:
將上面例子的代碼: nums = range(5)改為nums = list(range(5))
python 報錯TypeError: 'range' object does not support item assignment,解決方法