6x2KYqRT
6x2KYqRT

Reputation: 37

Alternative to itertools.compress()?

import itertools
  
  
ListA =['1', '2', '3', '4']
ListB = [None, None, 0, 1]

I have the two lists; I need to basically do itertools.compress(), but only None values don't count, so the "0" would be the same as the 1.

Upvotes: 1

Views: 348

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

The itertools.compress documentation tells you the implementation:

def compress(data, selectors):
    # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
    return (d for d, s in zip(data, selectors) if s)

This can be adjusted to only compress None like so:

>>> [d for d, s in zip(ListA, ListB) if s is not None]
>>> ['3', '4']

Alternatively, as @Barmar commented, you can use compress but perform an intermediate loop to convert the selectors into the truth values you want:

>>> compress(ListA, (e is not None for e in ListB))
>>> ('3', '4')

This is probably a superior solution.

Upvotes: 2

Related Questions