博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python:在列表中查找
阅读量:2288 次
发布时间:2019-05-09

本文共 2319 字,大约阅读时间需要 7 分钟。

本文翻译自:

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楼

参考:


#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)或根据需要阅读即可。

转载地址:http://oscnb.baihongyu.com/

你可能感兴趣的文章
Docker定制私有镜像
查看>>
Docker资源限制
查看>>
Docker容器跨主机通讯
查看>>
Docker单机编排docker-compose
查看>>
Docker数据管理
查看>>
Dockerfile创建镜像
查看>>
Docker镜像仓库搭建 图形化Harbor
查看>>
Kubernetes集群组件安装(二进制安装)
查看>>
阿里云ECS磁盘在线扩容后扩容磁盘
查看>>
K8S控制器Deployment
查看>>
Ambari安装
查看>>
使用ambari创建Hadoop集群
查看>>
KVM和Qemu的区别
查看>>
KVM
查看>>
NoSQL分类
查看>>
MongoDB安装
查看>>
MongoDB基础操作
查看>>
MongoDB用户权限管理
查看>>
Zabbix 安装配置
查看>>
zabbix自定义监控项
查看>>