Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i iterate through two lists with string elements in python with a condition

For example, I have two lists like

a = ["there", "is", "a", "car"]
b = ["i", "feel", "happy", "today"]

I want to compare a[0] and b[0]1, if there is any common alphabet between'there'and'i'` the result should be true or else it should be false

Output:

[False,False,True,True]

I was able to do it if it is just one element in a and b but cannot iterate through the list

a = ["there", "is", "a", "car" , "jill"]
b = ["i", "feel", "happy", "today" ,"jill"]
d = []
i = 0
for  word in range(len(a)):
    for word in range (len(b)):
        c = list(set(a[i]) & set(b[i]))
    if c == []:
            d.append(False)
    else:
            d.append(True)
i = i+1
print (d)
like image 589
Naveen Avatar asked Jan 26 '23 02:01

Naveen


2 Answers

Assuming you want to perform the tests in pairs, this is your code:

print([bool(set(x) & set(y)) for (x, y) in zip(a, b)])

Your input lists are of unequal length, so it is not clear to me what you want to do with "jill" (the b item unmatched if a).

A bit more details:

  • zip makes a list of pairs from a pair of lists (it actually makes a list of n-tuples from n lists, but in our case n == 2).
  • As you figured, constructing a set from a string returns the set of characters in the string.
  • & as a set operator is set intersection
  • constructing a bool value from a set return that set's non-emptiness.
  • Simple list comprehension constructs the result.
like image 142
Amitai Irron Avatar answered Jan 29 '23 19:01

Amitai Irron


Something like this should work:

d = [len(set(i)&set(j)) > 0 for i,j in zip(a,b)]

Testing:

>>> a = ["there", "is", "a", "car" , "jill"]
>>> b = ["i", "feel", "happy", "today" ,"jill"]
>>> d = [len(set(i)&set(j)) > 0 for i,j in zip(a,b)]
>>> d
[False, False, True, True, True]
>>> 
like image 44
lenik Avatar answered Jan 29 '23 19:01

lenik