简体   繁体   中英

Python. Compare list of words to list of letters

I have a list

stimuli_words = ["red","bird","ocean"]

and another list

stimuli_letters = ['b','i','r','d','r','e','d','o','c','e','a','n']

Is there a way to compare the second list to the first and return matched words? Order of words doesn't matter, but within-word letters should be in the right order.

You can do this:

stimuli_words = ["red","bird","ocean"]
stimuli_letters = ['b','i','r','d','r','e','d','o','c','e','a','n']
stimuli_string = ''.join(stimuli_letters)  # This becomes 'birdredocean'

for word in stimuli_words:
    if word in stimuli_string:
        print(word)
        # Do something else

Where basically first you create a string from the chars in stimuli_letters and then you search for each word in stimuli_words inside the string.

Of course this only works if the chars are in order in the second list. Otherwise it becomes exponentially complex.

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