0
string = 'get selected items from the list'

lst_keywords = ['list', 'selected', 'python', 'subset']

res = [ele for ele in lst_keywords if(ele in string)] 

then res = ['list', 'selected']

But I only want the first occurrence of element present in the string, like in the string since selected comes first I just want res to output selected only excluding the list element from res.

Any ideas of how I can achieve that?

2
  • 1
    next(ele for ele in lst_keywords if ele in string) Sep 24, 2019 at 10:52
  • @Christ_Rands @OP How does it answer the question? It gives the first item from lst_keywords that is in the string, i.e. "list"; it does not output the element (word) that is first in the string ("selected"). The latter appears what is being asked, given the penultimate paragraph.
    – 9769953
    Sep 24, 2019 at 11:43

1 Answer 1

1

Code

string = 'get selected items from the list'
lst_keywords = ['list', 'selected', 'python', 'subset']
v_ = [str1 for str1 in string.split() if str1 in lst_keywords][0]
print(v_)

Result

selected
3
  • Yup, the preferred way is what you have mentioned. Sep 25, 2019 at 3:05
  • Hey @AnswerSeeker, thanks for that answer , just want to know if I add one more element in lst_keywords like 'get selected' so now I have 5 items in the list and from the raw string since 'get selected' comes first so it should output that element from the list. Sep 27, 2019 at 11:24
  • For two connected words, algorithm will have to apply bigrams and perform a search. Sep 30, 2019 at 2:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.