Why can't I check if a string is a substring of each string in a list by using list comprehension?

huangapple go评论73阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年7月11日 04:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定