简体   繁体   中英

Remove an element from two lists

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?

Good use case for itertools.compress and filter :

list_a[:] = compress(list_a, list_b)
list_b[:] = filter(None, list_b)

Try it online!

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...

  1. 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 original list_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 by append()

  2. 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 lists

  3. Make a "mask". numpy can do this or you can make your own, perhaps with a list comprehension again over list_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.

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]

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))

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