Issue
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.
Solution
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
Answered By - JeffUK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.