我是 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
A 在此代码之上声明,其中的元素数量根据程序的输入文件而变化。目前我遇到了索引超出范围错误以及 A[i] 到 arr1[index1] 的分配。有任何想法吗?我似乎无法在 Python 中运行它。
谢谢!
最佳答案
您可以使用 +
或 +=
运算符来做到这一点:
>>> 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]
你的代码的问题是列表 arr1
和 arr2
是空的,所以
为尚不存在的索引赋值会引发 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]]
关于python - 如何在不使用 append,Python 的情况下将元素插入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17137184/