mercredi 8 novembre 2017

Boolean-Logical comparison of strings using list comprehension? (python)

My 1st Question on Stackoverflow!
Here's what I'm trying to do (in a single list comprehension):

1. Take in 2 strings containing boolean values
2. Compare the the relation of the bool-integers using logical operators
3. Return a list of boolean 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)
- string items are skipped in all other cases (0,0 & 0,1)

Example Logic:

A = "11111111111000000010"  
B = "11101010101010101010"  
L = []

for i in range(len(bools1)):
    if int(A[i]) + int(B[i]) == 2:
        L.append(1)
    elif int(A[i])==1 and int(B[i])==0:
        L.append(0)

Current Attempt:

L = [1 if int(x)+int(y)==2 else 0 if int(x)-int(y)==1 for x, y in zip( A, B )]

How do I avoid the syntax error that pops-up - pointing to the 'for'?

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

Side Question:
- With the load of iterating int() transformations,
should I just transform the strings to lists prior to the list comprehension?

Use Cases:
- Comparing strings representing the set of features (un)desired by a user/customer, and (un)available for a given service or product/service
- The return 1's would represent desiresMet and the return 0's would represent desiresUnmet
- Further derivatives/analysis could easily be done on the boolean list returned.

Aucun commentaire:

Enregistrer un commentaire