简体   繁体   中英

How can I remove specific index from list in python

I'm trying to figure out how to remove specific index from list, but I don't know how to fix my problem. Can someone help me to solve this?

First, I have to get some numbers from users using input.

numbers = int(input("input any numbers: "))
list_num = list(numbers)

Second, if list_num[0] == 1, remove that element.

Third, if list_num[i+1] == list_num[i], remove list_num[i+1].

So, if the initial list goes like this: list_num = [1,2,7,8,13,20,21] ,

the final list will be list_num = [2,7,13,20]

This is the program to be fixed:

 numbers = int(input("input any numbers:"))
 list_num = list(numbers)
 if list_num[0] ==1:
    list_num.remove(num[0])
 for i in range(1,len(list_num)-1, 1):
    if list_num[i] = list_num[i+1] -1:
         list_num.remove(num[i+1])
 print(list_num)

You can delete it by using keyword del . Here is the example.

my_list = [1, 2, 3, 4, 5]
del my_list[0] # 0 is the index

This will delete the first index of my_list. So the resultant list will be [2, 3, 4, 5]

Here is the section from the tutorial.

Please review your question again. Please correct your question because it is unclear what you are trying to achieve. These are the two conditions that i think you wish to achieve.

  1. if list[0] == 1 then remove that element.
  2. if list[i+1]-1 == list[i] then remove list[i+1]

First of all in line 6 of your code there is an error, it should be if == and not if = .The following code will achieve the above conditions.

numbers = int(input("Enter the limit for the list : "))

list_num = []

for i in range(0,numbers):
    list_num.append(int(input("list["+str(i)+"]: ")))

if list_num[0] == 1:
    list_num.remove(list_num[0])
try:
    for i in range(0,len(list_num)):
        if list_num[i] == list_num[i+1]-1:
            list_num.remove(list_num[i+1])
except:
    print list_num

Input: [1,2,7,8,13,20,21]

Output: [2,7,13,20]

There were several issues with your code including syntax, indentation and logic. I have formatted your code into a working manner. Good Luck.

numbers = input("input any numbers:")
list_num = list(numbers)

ret = []
for i,v in enumerate(list_num):
    if i == 0 and v == 1:
        continue
    if v == list_num[-1]:
        ret.append(v)
        break
    if v != list_num[i+1]:
        print v, list_num[i+1]
        ret.append(v)

print(ret)

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