代码之家  ›  专栏  ›  技术社区  ›  Jane Sully

python中数组的就地修改

  •  0
  • Jane Sully  · 技术社区  · 6 年前

    我发现这个问题要求对数组进行就地修改,以便将所有零移动到数组的末尾,并保持非零元素的剩余顺序。根据问题陈述,就地意味着不复制原始数组(这是从Leetcode中提取的,可以找到#283,移动零)

    for num in nums:
        if num == 0:
            nums.remove(num)
            nums.append(0)
    

    解决方案清晰易懂,所以我知道它在做它应该做的事情。

    indices = []
    for en, num in enumerate(nums): # get the index of all elements that are 0
        if num == 0:
            indices.append(en)
    
    for en, i in enumerate(indices): 
        new_i = i-en # use the index, accounting for the change in length of the array from removing zeros
        nums = nums[:new_i] + nums[new_i+1:] # remove the zero element
    nums = nums + [0] * len(indices) # add back the appropriate number of zeros at the end
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   bunbun    6 年前

    remove是否在内部复制数组以删除指定的元素?

    source code for lists , remove() 电话 listremove() :

    listremove(PyListObject *self, PyObject *v)
    {
        Py_ssize_t i;
    
        for (i = 0; i < Py_SIZE(self); i++) {
            int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
            if (cmp > 0) {
                if (list_ass_slice(self, i, i+1, (PyObject *)NULL) == 0)
                    Py_RETURN_NONE;
                return NULL;
            }
            else if (cmp < 0)
                return NULL;
        }
        PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
        return NULL;
    }
    

    here :

    arguments: list object, element to remove
    returns none if OK, null if not
    listremove:
        loop through each list element:
            if correct element:
                slice list between element's slot and element's slot + 1
                return none
        return null
    

    enter image description here