简体   繁体   中英

Python - Check if part of a string exists in a list and give the index of its match

I'm trying to get a piece of code to return the index of where the match was found within the list, so that another item can be compared to this index. (essentially allowing two separate strings to be compared to the same item on a list). I'm able to get the match if it matches exactly, but can't get it to work with a partial string. Here is some pseudo code to show what I have:

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']
str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

b = [i for i, s in enumerate(mylist) if str1 in s]
print(b)

So my question is how can I get the index of 'mno' to return so that I can compare str2 against it after the first check. If there's a better way around this problem id love to hear it

How about like this:

b = []
for i in str1.split():
    for idx, j in enumerate(mylist):
        if i in j:
            b.append(idx)

...or if you're looking for a list comprehension:

b = [idx for i in str1.split() for idx, j in enumerate(mylist) if i in j]

Output:

[4]

From the question, str1 in s will never be true since no element of mylist contains the entire str1 string.

Assuming word boundaries are important, you can split the string, then find indexes of the string containing that token

b = [] 
for s1 in str1.split():
    for i, s2 in enumerate(mylist):
        if s1 in s2:
            b.append(i)

Maybe this one can help!!

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']
str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

b = [i  for i, s in enumerate(mylist) for st in str2.split(' ') if st in s]
print(b)

Maybe it would be best to put this into a function?

str = 'does mno have anything to do with it?'
str2 = 'I think mn is there'
mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']

def are_you_here(str, list):
    return [list.index(x) for x in list if x in str]

are_you_here(str, mylist)
are_you_here(str2, mylist)

Output:

[4]
[]

This may help as in str2 you are searching specific keyword which is "mn" so we split str1 into simple list of words and then traverse the list to find occurrences of partial mn in items.

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']

str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

for i in str1.split(" "):
    for j in mylist:
    if i in j:
        print("match found and its for " + i + " which is partially exist in " + j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM