我编写了一个用于删除Web文章的函数,但我希望以某种方式对其进行调整,以使其能够检查该文章是否对我有利(基于关键字列表),如果不是,则将其忽略。我发现了几种检查一个字符串是否在另一个字符串中的方法,但是以某种方式我无法让它们在for循环中工作。这是该函数的一个简单示例:
combos = ['apple and pear', 'pear and banana', 'apple and peach', 'banana and kiwi', 'peach and orange']
my_favorites = ['apple', 'peach']
caps = []
for i in combos:
for j in my_favorites:
if j not in i:
continue
caps.append(i.upper())
print(caps)
如果不包括我最喜欢的水果中的至少一个,我想跳到循环的下一个迭代。但是列表中的所有字符串都通过了过滤器:
['APPLE AND PEAR', 'PEAR AND BANANA', 'APPLE AND PEACH', 'BANANA AND KIWI', 'PEACH AND ORANGE']
有人可以在这里解释我的理解不力吗?
您需要将caps.append(i.upper())添加到else条件。
combos = ['apple and pear', 'pear and banana', 'apple and peach', 'banana and kiwi', 'peach and orange']
my_favorites = ['apple', 'peach']
caps = []
for i in combos:
for j in my_favorites:
if j not in i:
continue
else:
caps.append(i.upper())
print(caps)