Home > Mobile >  string appears as subset of character in list element python
string appears as subset of character in list element python

Time:09-30

So far, I have:

my_list = ['hello', 'oi']
comparison_list = ['this hellotext', 'this oitext']

for w in my_list:
    if w in comparison_list: print('yes')

However, nothing prints because no element in my_list equals any element in comparison_list.

So how do I make this check as a subset or total occurance?

Ideal output:

yes
yes

CodePudding user response:

You are checking the occurrence of the complete string in the list currently. Instead you can check for the occurrence of the string inside each comparison string and make a decision. A simple approach will be to re-write the loop as below

for w in my_list:
    # Check for every comparison string. any() considers atleast 1 true value
    if any([True for word in comparison_list if w in word]):
        print('yes')

CodePudding user response:

It's because you're comparing w to the list elements. If you wanna find w in each string in your comparison_list you can use any:

my_list = ['hello', 'oi', 'abcde']
comparison_list = ['this hellotext', 'this oitext']

for w in my_list:
    if any(w in s for s in comparison_list):
        print('yes')
    else:
        print('no')

I added a string to your list and handle the 'no' case in order to get an output for each element

Output:

yes
yes
no

CodePudding user response:

Edited Solution: Apologies for older solution, I was confused somehow.

Using re module , we can use re.search to determine if the string is present in the list of items. To do this we can create an expression using str.join to concatenate all the strings using |. Once the expression is created we can iterate through the list of comparison to be done. Note | means 'Or', so any of the searched strings if present should return bool value of True. Note I am assuming there are no special characters present in the my_list.

 import re
 reg =  '|'.join(my_list)
 for item in comparison_list:
     print(bool(re.search(reg, item)))
  • Related