英文:
Why can't I check if a string is a substring of each string in a list by using list comprehension?
问题
当我运行它时,它指向for
并说无效的语法。为什么这不起作用?
英文:
I have the following code:
MFII_files = ['patrick', 'domccc', 'joseph', 'harry']
file_name = 'ccc'
if file_name in MFII_file for MFII_file in MFII_files:
print('yes')
But when I run it, it says invalid syntax pointing to the for
. Why does this not work?
答案1
得分: 3
使用any
来执行此检查。
if any(file_name in MFII_file for MFII_file in MFII_files):
any
接受一个可迭代对象并返回一个指示可迭代对象中是否有任何元素为真的结果。在这种情况下,我们可以方便地传递一个生成器表达式。
英文:
Use any
to perform this check instead.
if any(file_name in MFII_file for MFII_file in MFII_files):
any
takes an iterable and returns a result indicating whether any element of the iterable was true. In this case, we can conveniently pass a generator expression.
答案2
得分: 0
如果您想使用列表推导,那么我建议类似这样:
selection =
if selection:
print('yes')
英文:
If you want to use list comprehension, then I suggest something like:
selection =
if selection:
print('yes')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论