Home > front end >  How to save all element index after removing element in python
How to save all element index after removing element in python

Time:12-29

sentence = [[1,0,3],[2,0,0],[0,0,5]]
empty = []
for element in sentence :
    for icelement in element :
        if not icelement == 0:
            empty.append(icelement)
        
         
        
print(empty)
print(empty[2]) #this should give 3 or empty[8] should give 5

I did many attempt but stil having problem. I know this is because python automatically updating the elements index but dont know how to control it. Any suggestion will help me.

num = [1,0,4,5]
print(num[3]) #gives 5
for n in num :
    if n == 0:
        num.remove(n)

print(num[3])# doesnt exist.

CodePudding user response:

You want to preserve the position in the original flattened list while removing some elements?

The options are either flatten the list, leave the zeroes in place; just ignore them.

empty = [item for sublist in sentence for item in sublist] #[1, 0, 3, 2, 0, 0, 0, 0, 5]
print(empty[2]) # returns 3

Or do something with a dictionary, use the original position in the flattened list as the key.

count = 0
empty = {}
for element in sentence :
    for icelement in element :
        if not icelement == 0:
            empty[count] = icelement
        count  =1

print(empty[2]) # returns 3

CodePudding user response:

The indexes of python starts with 0

It gives you back the list:

[1, 3, 2, 5]

so to get the second element we should do:

print(empty[1])

so the code looks like this now

sentence = [[1,0,3],[2,0,0],[0,0,5]]
empty = []
for element in sentence :
    for icelement in element :
        if not icelement == 0:
            empty.append(icelement)
        
         
        
print(empty)
print(empty[1])

Output:

[1, 3, 2, 5]
3

CodePudding user response:

From your code and the description of the output, it looks like you want to flatten you nested list and remove the zeros. At the same time you want to retain the original flattened indices.

This is not possible with a list as the indices necessarily go from 0 to len(the_list).

You can either keep the zeros:

sentence = [[1,0,3],[2,0,0],[0,0,5]]

empty = [i for l in sentence for i in l]
# [1, 0, 3, 2, 0, 0, 0, 0, 5]

Or use a different container. Dictionaries enable to have arbitrary keys:

from itertools import chain

empty = {i:v for i,v in
         enumerate(chain.from_iterable(sentence))
         if v}
# {0: 1, 2: 3, 3: 2, 8: 5}

empty[2] 
# 3

empty[8]
# 5


CodePudding user response:

you can write the same loop in one line and it gives the same result as your code.

sentence = [[1,0,3],[2,0,0],[0,0,5]]

empty= [icelement for element in sentence for icelement in element if icelement != 0]
print(empty)

output:

[1,3,2,5]
  • Related