Python:在列表中查找

本文翻译自:Python: Find in list

I have come across this: 我遇到了这个:

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

but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string). 但有时它不能与我的所有项目一起使用,就像在列表中没有识别它们一样(当它是字符串列表时)。

Is this the most 'pythonic' way of finding an item in a list: if x in l: ? 这是在列表中查找项目的最“ pythonic”方式: if x in l:吗?


#1楼

参考:https://stackoom.com/question/e2V8/Python-在列表中查找


#2楼

如果您要查找一个元素,或者要在next查找None使用default,如果在列表中未找到该元素,则不会引发StopIteration

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

#3楼

Check there are no additional/unwanted whites space in the items of the list of strings. 检查字符串列表中的项目是否没有其他多余的空格。 That's a reason that can be interfering explaining the items cannot be found. 这就是可能无法解释项目的原因。


#4楼

虽然Niklas B.的答案非常全面,但是当我们想在列表中查找某项时,有时获得其索引很有用:

next((i for i, x in enumerate(lst) if [condition on x]), [default value])

#5楼

Finding the first occurrence 寻找第一次出现

There's a recipe for that in itertools : itertools有一个配方:

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

For example, the following code finds the first odd number in a list: 例如,以下代码查找列表中的第一个奇数:

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

#6楼

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']): 如果list元素等于一个项目([example]在['one','example','two']中):

    if item in your_list: some_function_on_true()

    'ex' in ['one','ex','two'] => True ['one','ex','two']中的'ex'=>真

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

  2. if list element is like an item ('ex' is in ['one,'example','two'] or 'example_1' is in ['one','example','two']): 如果list元素一个项目(“ ex”在['one,'example','two']或'example_1'在['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. 然后只需检查len(matches)或根据需要阅读即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值