解决:python中出现:list assignment index out of range

报错:IndexError: list assignment index out of range
问题:空数组不可指定位置

解决方案:使用append

<ipython-input-1-d3d3fbddf8a1> in reverse(test_set)
      3     reverse_test_set=[]
      4     for i in range(n):
----> 5         reverse_test_set[i]=test_set[n-i-1]


IndexError: list assignment index out of range

原代码

def reverse(test_set):
    n=len(test_set)
    reverse_test_set=[]
    for i in range(n):
        reverse_test_set[i]=test_set[n-i-1]
    return reverse_test_set

改为:

def reverse(test_set):
    n=len(test_set)
    reverse_test_set=[]
    for i in range(n):
        #reverse_test_set[i]=test_set[n-i-1]
        #空数组不能直接指定位置
        reverse_test_set.append(test_set[n-i-1])
    return reverse_test_set

你可能感兴趣的:(python,debug)