I have list_a and list_b. Both of these lists have items in an order.
Each time I encounter a 0 in list_b, I want to remove from list_a AND list_b the entry associated with that index. I am not sure how to do that.
# Before modification
list_a = [ '2019', '2020', '2021', '2022', '2023' ]
list_b = [ 40, 0, 30, 0, 9 ]
#After modification
list_a = [ '2019', '2021', '2023' ]
list_b = [ 40, 30, 9 ]
Any clue on how to approach this?
CodePudding user response:
There are probably 100 ways to do this, and I'm sure you'll get diverse responses. If you're interested in learning this, you should try a couple...
Use a for-loop over an index. Before the loop, make 2 new lists like
list_a_new
,list_b_new
and then use the for loop to loop over the index of the originallist_b
. test the object you get out. Use a conditional statement. If the object is not zero, get the items from the original lists at the same index position and add it to both of the new results byappend()
Use a list comprehension for both of the new lists and use
enumerate(list_b)
inside to get the same type of info and see if you can do a list comprehension for both new listsMake a "mask".
numpy
can do this or you can make your own, perhaps with a list comprehension again overlist_b
to make a mask of booleans like[False, True, False, True, ...]
Use that mask as the basis of another list comprehension to get new_a and new_b
Try a couple and edit your post if you are stuck! You'll improve your skills.
CodePudding user response:
Good use case for itertools.compress and filter:
list_a[:] = compress(list_a, list_b)
list_b[:] = filter(None, list_b)
CodePudding user response:
Here's a solution using a traditional for-loop to iterate over items from list_a
paired (using zip()
) with items from list_b
:
new_a = []
new_b = []
for a, b in zip(list_a, list_b):
if b != 0:
new_a.append(a)
new_b.append(b)
Or you could use a couple of list comprehensions:
new_a = [a for a, b in zip(list_a, list_b) if b != 0]
new_b = [b for b in list_b if b != 0]
You do it all in one line but readability suffers:
new_a, new_b = map(list, zip(*((a, b) for a, b in zip(list_a, list_b) if b != 0)))
If you don't mind modifying your original lists it becomes slightly less unreadable:
list_a[:], list_b[:] = zip(*((a, b) for a, b in zip(list_a, list_b) if b != 0))
CodePudding user response:
As mentioned by other users there are many ways
list_a2 = [list_a[i] for i in range(len(list_b)) if list_b[i]!=0]
list_b2 = [list_b[i] for i in range(len(list_b)) if list_b[i]!=0]