简体   繁体   中英

how to delete element of array on index number 2 without using in built function?

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

try the following:


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)

alternatively if you don't want to slice you could reconstruct the array as follows:

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)
from array import *
a = array('i',[1,3,3,4,5])
for e in range(len(a)):
    if(e == 2):
        continue
    else:
        print(a[e],end=" ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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