Python: Find in list

后端 未结 10 826
故里飘歌
故里飘歌 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 10:58

    If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

    first_or_default = next((x for x in lst if ...), None)
    

提交回复
热议问题