简体   繁体   English

从列表中提取关键字,然后使用和

[英]Extract keywords from a list then use `and`

Well I don't know how to explain this. 好吧,我不知道该怎么解释。 For example I have the following code: 例如,我有以下代码:

if 'foo' and 'bar' in 'foobar':
    print('foobar')

I want to use some keywords to check the sting, and my question is, now I'm trying to put these keywords in a list like this: 我想使用一些关键字来检查刺痛,我的问题是,现在我试图将这些关键字放在这样的列表中:

keywords = ['foo', 'bar']

But how can I use them now? 但是,现在如何使用它们? If I use for to extract them like this: 如果我for像这样提取它们:

for i in keywords:
    if i in 'foobar':
        print('foobar')

But this will print foobar twice. 但这将两次打印foobar

You can use a generator expression to loop over all the keywords and check if they are all contained in 'foobar' . 您可以使用生成器表达式遍历所有关键字,并检查它们是否都包含在'foobar' Using all will also allow it to short-circuit upon finding the first False . 使用all也将使其在找到第一个False短路。

if all(i in 'foobar' for i in keywords):
    print('foobar')

The analog to this is if you want to print if any of the keywords are found, you can use 与此类似,如果您要在找到任何关键字的情况下进行print则可以使用

if any(i in 'foobar' for i in keywords):
    print('foobar')

If you want to stick with a loop, you could use a for-else . 如果要坚持循环,可以使用for-else

for i in keywords:
    if i not in 'foobar':
        break
else:
    print('foobar')

If any i is not in 'foobar' , the loop will exit and skip over the else section. 如果任何i不在'foobar' ,则循环将退出并跳过else节。 The else if a for-else is only entered if the loop exits without break ing, which in this case will only happen if every i is in 'foobar' . else ,如果for-else只有当退出循环,而不进入break ING,在这种情况下,如果每一个只会发生i'foobar'

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM