如何在不使用append,Python的情况下将元素插入到数组中?

Tud*_*nar 3 python arrays list

我是Python的初学者,在不使用append()函数的情况下将元素插入数组时遇到了一些麻烦.

这是我的代码的一部分,我希望它足够详细,但如果它有帮助,请随时询问更多细节:

#other code
arr1 = []
arr2 = []
index1 = 0
index2 = 0

for i in range(0, len(A)):
    if A[i] < A[r]:
        arr1[index1] = A[i]
        index1 = index1 + 1
    elif A[i] > A[r]:
        arr2[index2] = A[i]
        index2 = index2 + 1 
    #other code
Run Code Online (Sandbox Code Playgroud)

A在此代码之上声明,并且其中的元素数量根据程序的输入文件而变化.目前我得到索引超出范围错误和A [i]到arr1 [index1]的分配.有任何想法吗?我似乎无法在Python中使用它.

谢谢!

Ash*_*ary 7

您可以使用++=运营商:

>>> lis = []
>>> lis = lis + [1]
>>> lis
[1]
>>> lis = lis + [2]
>>> lis
[1, 2]
>>> lis += [3]  # += acts like list.extend, i.e changes the list in-place
>>> lis
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

与您的代码的问题是,名单arr1arr2是空的,所以分配值,这还不存在的索引会提高IndexError.

for i in range(0, len(A)):
    if A[i] < A[r]:
        arr1 = arr1  + [A[i]]

    elif A[i] > A[r]:
        arr2 = arr2 + [A[i]]
Run Code Online (Sandbox Code Playgroud)