Here's what I'm trying to do (in a single list comprehension):
1. Compare the the relation of 2 bool-integer lists using logical operators
2. Return a list of bool-int values where:
- 1 is returned when both a,b values are 1 (1,1)
- 0 is returned when a==1 and b==0 (1,0)
- other cases are skipped, as in (0,0 & 0,1)
Example Logic:
A = [1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,0]
B = [1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
L = []
for i in range(len(B)):
if A[i] + B[i] == 2:
L.append(1)
elif A[i]==1 and B[i]==0:
L.append(0)
Expected Output for print(L):
[1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1]
My Attempt: (syntaxError points to the 'for')(and it's a bit long)
L = [1 if x+y == 2 else 0 if x-y == 1 for x,y in zip(A, B)]
Best Answer by Wander Nauta (Pythonic and fast)
L = [y for x, y in zip(A, B) if x]
.
Couple of My Reference Points:
- add-sum-of-values-of-two-lists-into-new-list
- if-else-in-a-list-comprehension
- elif-in-list-comprehension-conditionals
Use Cases:
- Comparing lists representing the set of features (un)desired by a user/customer, and (un)available for a given product/service
- The returned 1's would represent desires_met and 0's would represent desires_unmet
- Further derivatives/analysis could easily be done on the boolean list returned.