[英]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()
的生成器表达式的范围内,您从函数返回的所有内容都是True
或False
。 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.