1

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.

  • possible duplicate of [In Python, how do I find the index of an item given a list containing it?](http://stackoverflow.com/questions/176918/in-python-how-do-i-find-the-index-of-an-item-given-a-list-containing-it) – Cfreak Mar 15 '13 at 20:31
  • try to add some input and expected output, it is not clear what you really want to do. – Facundo Casco Mar 15 '13 at 20:32
  • I will try - however I have to think about how, because I hardly have an idea what I'm doing myself. – Maarten Boogaard Mar 15 '13 at 20:36

1 Answers1

10

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

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
  • Sorry, but apparently my question was rather badly formatted; I edited it to make it seem more clear. I don't have trouble with the new list I'd have to make, I just need to figure out how to catch the index of the item of the array the loop is currently at when it returns true upon searching in the string. – Maarten Boogaard Mar 15 '13 at 20:42
  • You just did it!! Thanks so much for your amazing reading comprehension! I know my question was a bunch of bullshit - so understand wtf I meant was quite hard. Thanks for your time. Enumerate is something I personally won't touch yet myself, I have to stay sane. However, your code works perfectly, so that's alright. – Maarten Boogaard Mar 15 '13 at 20:52
  • Wouldn't it be quite easy to make it return ['text', 'words'] instead of the index too, then? Just wondering, for myself to learn. – Maarten Boogaard Mar 15 '13 at 21:00
  • sure, to do that just use `filter(lambda x: x in text, words)` – Facundo Casco Mar 15 '13 at 21:01