简体   繁体   English

Python:如何使用(列表中项目的项目中为“str”)?

[英]Python: How to use if any(“str” in item for item in list)?

The code snippet below returns an error that global name 'item' is not defined. 下面的代码段返回一个错误,即未定义全局名称“item”。 How do I use if any(...) correctly to search for and print a string if found in a list? 如果在列表中找到,如何正确搜索和打印字符串,如何使用(...)?

def walk:
    list = ["abc", "some-dir", "another-dir", ".git", "some-other-dir"]
    if any (".git" in item for item in list):
        print item,

You don't. 你没有。 Don't use any() if you want to enumerate all the matching items. 如果要枚举所有匹配项,请不要使用any() The name item only exists in the scope of the generator expression passed to any() , all you get back from the function is True or False . 名称item仅存在于传递给any()的生成器表达式的范围内,您从函数返回的所有内容都是TrueFalse The items that matched are no longer available. 匹配的项目不再可用。

Just loop directly over the list and test each in an if test: 只需直接遍历列表并在if测试中测试每个:

for item in lst:
    if ".git" in item:
        print item,

or use a list comprehension, passing it to str.join() (this is faster than a generator expression in this specific case ): 或使用列表str.join() ,将其传递给str.join()在这种特定情况下,这比生成器表达式更快 ):

print ' '.join([item for item in list if ".git" in item])

or, using Python 3 syntax: 或者,使用Python 3语法:

from __future__ import print_function

print(*(item for item in list if ".git" in item))

If you wanted to find just the first such a match, you can use next() : 如果你想找到第一个这样的匹配,你可以使用next()

first_match = next(item for item in list if ".git" in item)

Note that this raises StopIteration if there are no such matches, unless you give next() a default value instead: 注意,如果没有这样的匹配,这会引发StopIteration ,除非你给next()一个默认值:

first_match = next((item for item in list if ".git" in item), None)
if first_match is not None:
    print first_match,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中将列表中的任何项目用作拆分值? - How to use any item in a list as a split value in Python? 如何检查列表是否包含 python 列表中的任何项目 - How to check if list contains any item from list in python 在 python 中将字符串转换为列表时,str[n] 将 ''," 计为列表项 - When a string is converted into a list in python, str[n] counts ''," as a list item 用Python将另一个列表中的任何项目 - Python any item from a list in another list 对于 list1 的任何项目,如果它是 python 中的 list2 - for any item of list1 if it is list2 in python 如何查看列表中的任何项目是否在 Python 中的字符串内? - How to see if any item in a list is inside a string in Python? Python:过滤或搜索str列表时将范围应用于通配符(需要将任何没有10位数字的str列表项添加到列表中) - Python: apply a range to wildcard when filtering or searching a str list (need to add any str list item that doesn't have a 10-digit number to a list) 按str(item)的长度排序列表 - Sort list by length of str(item) TypeError:序列项 0:预期的 str 实例,在 python 3 中找到的列表 - TypeError: sequence item 0: expected str instance, list found in python 3 Python:如果列表中的任何变量存在,则打印该项目 - Python: If any variable in list exists, then print the item
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM