Python数组和Java中的数组一样吗?

2024-09-29 23:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在班上有一个任务,用Java和Python实现一些东西。我需要用两种语言实现IntegerStack。所有的值都应该保存在一个数组中,还有一些元数据值,比如head()index。你知道吗

当我实现this is Java时,我只创建一个最大大小的数组(我选择):

public class IntegerStack {
    public static int MAX_NUMBER = 50;
    private int[] _stack;
    private int _head;

    public IntegerStack() {
        _stack = new int[MAX_NUMBER];
        _head = -1;
    }

    public boolean emptyStack() {
        return _head < 0;
    }

    public int head() {
        if (_head < 0)
            throw new StackOverflowError("The stack is empty."); // underflow

        return _stack[_head];
    }
    // [...]
}

我真的不知道如何在Python中做到这一点。我查看了一些教程,它们都说python中的数组具有my_array = [1,2,3]语法。但它是不同的,因为我可以使用它作为一个列表,并附加我想要的项目。所以我可以创建一个for循环,并将50个零元素初始化到一个Python数组中,但它会和Java中的一样吗?我不清楚Python列表与数组有何不同。你知道吗


Tags: 语言number列表newreturnisstack数组
3条回答

首先,在Python中需要区分数组和列表。 这里所说的是list类,但也有actual arrays,它们与Java中的数组大致相同。你知道吗

Python的{{CD1>}类似于java的^ {< CD3>},和C++的^ {CD4>}类似。你知道吗

换句话说,这里有三种可能的解决方案:

  1. 使用简单的list,只需向其添加元素。你知道吗
  2. 使用python的array最接近Java的数组。你知道吗
  3. 使用python的deque。你知道吗

关于list的使用,如果您的目标是用N个空元素初始化它,那么您可以做的是:

N = 10     # or any other number
my_list = [0] * N # 0 is the element here for the list to be filled with

或者更别致的方法

from itertools import repeat
my_list = list(repeat(0, N))

如果您想实现接近java版本的东西,可以通过导入numpy来使用numpy数组。Numpy数组是类似的,因为它们和java一样是不可变的对象。然后可以在构造函数中编写:

    _stack = np.zeros(MAX_NUMBER)

否则,您可以使用python本身的可变列表对象,在本例中,列表实际上已经是一个堆栈,正如您在data structures的python文档中看到的那样:

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

    >>> stack = [3, 4, 5]
    >>> stack.append(6)
    >>> stack.append(7)
    >>> stack
    [3, 4, 5, 6, 7]
    >>> stack.pop()
    7
    >>> stack
    [3, 4, 5, 6]
    >>> stack.pop()
    6
    >>> stack.pop()
    5
    >>> stack
    [3, 4]

但是,第一个版本的性能更高,因为每次更改可变的python对象时都必须复制它们,而不可变的对象只是创建的,没有名称引用它的旧对象被垃圾收集。你知道吗

在python中,如果您声明如下数组:

myarray = []

您正在声明一个head为-1的空数组,可以使用.append()函数将值附加到该数组中,并以与java中相同的方式访问它们。无论出于何种目的,它们都是同一件事

相关问题 更多 >

    热门问题