简体   繁体   English

在 Python 3 中反转数组时出现 IndexError

[英]IndexError when reversing an array in Python 3

I tried to reverse an array in Python, but I got an IndexError: list index out of range .我试图在 Python 中反转一个数组,但我得到一个IndexError: list index out of range Can anyone help me find out what's my problem?谁能帮我找出我的问题?

Here's my code:这是我的代码:

def reverseArray(a,n):
    b = []
    
    for i in range(n + 1):
        b.insert(0, a[i])
    
    return b

Error:错误:

Traceback (most recent call last):
  File "/tmp/submission/20220709/03/24/hackerrank-6dc9d7d54d580ec91f519f2a6455587b/code/Solution.py", line 33, in <module>
    res = reverseArray(arr,arr_count)
  File "/tmp/submission/20220709/03/24/hackerrank-6dc9d7d54d580ec91f519f2a6455587b/code/Solution.py", line 21, in reverseArray
    b.insert(0, a[i])
IndexError: list index out of range

Since reverseArray is the call which caused the issue, let's fix it first由于reverseArray是导致问题的调用,让我们先修复它

Refactoring your code we get :重构您的代码,我们得到:

def reverseArray(a, n):  # rather unpythonic
    b = []
    for i in range(n - 1, -1, -1):
        b.append(a[i])
    return b

Which works like this taking two arguments :像这样使用两个参数:

>>> foo = [1, 2, 3]      
>>> reverseArray(foo, 3)
[3, 2, 1]

But that is unpythonic and can be alot better, something like this :但这是非pythonic,可以更好,像这样:

def reversed_array(a):
    return [*reversed(a)]

Which is exactly the same thing except it takes one less argument of length这完全一样,只是它少了一个长度参数
Example use :示例使用:

>>> foo = [1, 2, 3]
>>> reversed_array(foo) 
[3, 2, 1]

Since the list "b" doesn't contain any element , so b.insert(0,a[i]) won't work .由于列表“b”不包含任何元素,所以b.insert(0,a[i])将不起作用 What you have to do instead is , use b.append(a[i]) , which in your case , will get the job done.您需要做的是,使用b.append(a[i]) ,在您的情况下,它将完成工作。

If you are using it like this:如果您像这样使用它:

reverseArray([], 0)
reverseArray([1, 2, 3], 3)

The actually problem is:实际的问题是:

range(n + 1)

Cause range creates sequence from 0 to n - 1:原因范围创建从 0 到 n - 1 的序列:

range(0) # empty seq
range(3) # 0, 1, 2

So you simply need do it like this:所以你只需要这样做:

def reverseArray(a: list, n: int):
    b = []
    
    for i in range(n): 
        b.insert(0, a[i])
    
    return b

But there is shorter, faster and more pythonic way to do it:但是有更短、更快和更 Pythonic 的方式来做到这一点:

a = [1, 2, 3]
reversed_a = a[::-1]
>>> reversed_a
[3, 2, 1]

Actually there's a quick and "pythonic" way to reverse an array in Python.实际上,有一种快速且“pythonic”的方法可以在 Python 中反转数组。 You can use the Array Slicing .您可以使用数组切片 Put a pair of brackets after your array just like calling an element.在数组后面放一对括号,就像调用元素一样。 For example, list1 = [1, 2, 3, 4, 5, 6] .例如, list1 = [1, 2, 3, 4, 5, 6] You can use the array slicing to reverse it like this: list = list[::-1] .您可以像这样使用数组切片来反转它: list = list[::-1] This is a very use ful skill in Python, and it's capable for all iterable items.这是 Python 中非常有用的技能,它适用于所有可迭代的项目。 For more informations about slicing in Python, see here .有关 Python 中切片的更多信息, 请参见此处

Array slicing is just a simple way to reverse.数组切片只是一种简单的反转方法。 Now let's get back to our question.现在让我们回到我们的问题。 The goal is to reverse the given array.目标是反转给定的数组。 Instead of the normal hard way, we can think the problem reversely .我们可以反过来思考问题,而不是通常的困难方式。 In your original code you were enumerating the array from start to end, which is a hard way to control the index of the array.在您的原始代码中,您从头到尾枚举数组,这是控制数组索引的一种困难方法。 Now let's enumerate it from back to start.现在让我们从头开始列举它。 So for i in range(n + 1) can be replaced with for i in range(n - 1, -1, -1) .因此for i in range(n + 1)可以替换for i in range(n - 1, -1, -1) This line of code enumerates from -1 to 0. Inside the for-loop, you can directly add a[i] in b (Because is in reverse order).这行代码从-1到0枚举。在for循环里面,可以直接在b里面加上a[i] (因为是倒序的)。 After that, the code for this method will be:之后,此方法的代码将是:

def reverse_array(array):    # Follow PEP8!
    res_array = []
    for i in range(len(array) - 1, -1, -1):
        res_array.append(array[i])
    return res_array

And here's an example:这是一个例子:

>>> example = [1, 2, 3, 4, 5, 6]
>>> reverse_array(example, 6)
[6, 5, 4, 3, 2, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM