-1

I want to zip two lists. For example:

a = ['a', 'b', 'c', 'd']
b = [0, 2, 1, 4]

And I have to left in the list only objects that don't match with 0. So for lists a and b I have to get list c:

c = ['b', 'c', 'd']

How can I do this with python? I tried using loop, but it works too long. Maybe I have to use zip() method, but I don't know exactly how to use it :(

quamrana
  • 37,849
  • 12
  • 53
  • 71
smihds
  • 1
  • 1
  • https://stackoverflow.com/questions/1663807/how-do-i-iterate-through-two-lists-in-parallel – Swifty Oct 23 '22 at 14:26
  • [Similar](https://stackoverflow.com/questions/74157557/how-can-we-check-if-something-other-than-a-value-in-a-list-in-python) – cards Oct 23 '22 at 15:51

3 Answers3

2

You could combine zip with list comprehension as follows:

a = ['a', 'b', 'c', 'd']
b = [0, 2, 1, 4]

c = [x for (x,y) in list(zip(a,b)) if y != 0]

outputs: ['b', 'c', 'd']

Damzaky
  • 6,073
  • 2
  • 11
  • 16
  • Thank you! But what do I have to do if I have a lot of lists like list b and I have to match all these lists with list like a? – smihds Oct 23 '22 at 14:41
  • 1
    What you must do is to ask a new question on this site explaining how these `b` lists work, giving a few examples, plus the code you've already tried. – quamrana Oct 23 '22 at 15:16
0

It seems a perfect job for compress from itertools

from itertools import compress

a = ['a', 'b', 'c', 'd']
b = [0, 2, 1, 4]

print(*compress(a, b))
cards
  • 3,936
  • 1
  • 7
  • 25
0
c = [x for x, y in zip(a, b) if y != 0]

This will work fine when both lists have the same length. If list a was longer and you'd want the extra elements out too, you could use this version:

from itertools import zip_longest

c = [x for x, y in zip_longest(a, b) if y != 0 and x is not None]
isCzech
  • 313
  • 1
  • 1
  • 7