简体   繁体   English

在python中定义一个add函数

[英]defining an add function in python

I need help with defining an add function in python.我需要在 python 中定义 add 函数的帮助。 This is my first time writing in python so I have trouble with a lot of the formatting.这是我第一次用 python 编写,所以我在很多格式方面遇到了麻烦。 I need to define an add function for an arraylist that shifts one position all the items j>=i, insert an element at position i of the list and increment the number of elements in the list Inputs: i: Index that is integer non negative and at most nx: Object type, ie, any object This is what I have written so far:我需要为一个数组列表定义一个添加函数,该函数将所有项 j>=i 移动一个位置,在列表的位置 i 插入一个元素并增加列表中元素的数量输入:i:非负整数索引最多nx:对象类型,即任何对象这是我到目前为止所写的:

def add(self, i : int, x : object) :
    if i>0 & i<self.size():

        for n in range(i, self.size())

    else:
        pass 

Now I wrote some psuedocode and was wondering if it would work:现在我写了一些伪代码,想知道它是否有效:

def(add(self, i : int, x : object) :
  declare new empty array of size n+1
 if i>0 and i<=n:
   for(i to arr length):
    put i into new array
 else:
  pass

所以,基本上python内置了这个。

mylist.insert(index, element)

对于已经内置的 D:

lst.insert(index, element)
def __init__(self, iitems):
    self.items = iitems
    self.size = len(self.items)

def add(self, i, x):
    ret = self.items[:i]
    ret.append(x)
    ret.extend(self.items[i:])
    self.items = ret
    self.size += 1

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

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