如何在不使用内置函数的情况下删除索引编号2上的数组元素?

时间:2019-06-21 08:57:05

标签: python

from array import *
arr = array('i',[])
length = int(input("Enter the length of array: "))
for i in range(length):
  x = int(input("Enter the next value: "))
  arr.append(x)
print(arr)
val = int(input("Enter the number you want to delete:"))
k = 0
for e in arr:
  if e ==val:
    print(arr)
    break
  k = k+1

1 个答案:

答案 0 :(得分:0)

尝试以下操作:


from array import *
arr = array('i',[])
length = int(input("Enter the length of array: "))
for i in range(length):
  x = int(input("Enter the next value: "))
  arr.append(x)
print(arr)
val = int(input("Enter the number you want to delete:"))
k = 0
delCount = 0
for (index, e) in enumerate(arr):
  if e == val:
    arr = arr[0:index-delCount] + arr[index+1-delCount:]
    delCount+=1
  k = k+1
print(arr)

或者,如果您不想切片,则可以按以下方式重建数组:

from array import *
arr = array('i',[])
length = int(input("Enter the length of array: "))
for i in range(length):
  x = int(input("Enter the next value: "))
  arr.append(x)
print(arr)
val = int(input("Enter the number you want to delete:"))
k = 0
tempArr = array('i',[])
for e in arr:
  if e != val:
      tempArr.append(e)
  k = k+1
arr = tempArr
print(arr)