简体   繁体   中英

Python - How to check whether a string contains an item from a list, and when returns true, have the item from the list as index usable in the loop

Basically how I'd like it to be, is:

  • Loop that checks if string contains one of the strings/items from the list. Basically, "for when current index of list returns true upon finding, append that item as string to a new list"

Example from another post:

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for any("abc" in s for s in some_list):
    #s isn't the index, right?

Well, the question basically is, how do I do the above. Sorry for my poor formatting and English, and such.

Example:

I have a string "La die la Blablabla and flowers are red"

I have an array TheArray , ['Blablabla', 'thisonewillnotbefound', 'flowers', 'thisonenoteither', 'red']

And I need a loop that goes through every item in the array, and whenever it finds one that exists in it, it will be appended to a completely new list.

This would give you a list of indexes of the list where the word was found in the text

>>> text = 'Some text where the words should be'
>>> words = ['text', 'string', 'letter', 'words']
>>> [i for i, x in enumerate(words) if x in text]
[0, 3]

enumerate will take an iterator and give another one with tuples where the first element is an index starting at 0 and the second is an element from the iterator you passed to it.

[i for i, x in ...] is a list comprehension is just a short form of writing a for loop

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