Python: Find in list

后端 未结 10 726
故里飘歌
故里飘歌 2020-11-22 10:15

I have come across this:

item = someSortOfSelection()
if item in myList:
    doMySpecialFunction(item)

but sometimes it does not work with

10条回答
  •  -上瘾入骨i
    2020-11-22 10:47

    You may want to use one of two possible searches while working with list of strings:

    1. if list element is equal to an item ('example' is in ['one','example','two']):

      if item in your_list: some_function_on_true()

      'ex' in ['one','ex','two'] => True

      'ex_1' in ['one','ex','two'] => False

    2. if list element is like an item ('ex' is in ['one,'example','two'] or 'example_1' is in ['one','example','two']):

      matches = [el for el in your_list if item in el]

      or

      matches = [el for el in your_list if el in item]

      then just check len(matches) or read them if needed.

提交回复
热议问题