如何检查集合中的每个字符串是否包含列表中的每个字符串?

2024-06-16 13:02:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个标题列表和一组字符串。我想检查列表中的每个标题是否在集合中的任何字符串中。如果列表中的字符串与集合中的字符串完全相同,则代码可以正常工作,但如果集合中的字符串“包含”列表中的字符串,则我希望此代码可以正常工作。这是我的密码:

for link in deduplicated_list:
    rdeep = requests.get(link)
    soup_deep = BeautifulSoup(rdeep.text, 'html.parser')
    if any(ele in str(soup_deep.title) for ele in list_of_books):
        print(soup_deep.title)

Tags: 字符串代码in密码标题列表fortitle
2条回答
list1 = ["cat", "dog", "bird"] 
set2 = ["Book of cats", "Book of elephants", "Book of ants"]

for animal in list1:
    for book in set2:
        if animal in book:
            print(f"FOUND, {animal} in '{book}'")

一个Pythonic方法是链接for loops

myset = {"cat meow", "dog ruff", "bird chirp"}

mylist1 = ["cat", "dog"]
mylist2 = ["run", "fun"]

any(animal in animal_sound for animal in mylist1 for animal_sound in myset)
any(animal in animal_sound for animal in mylist2 for animal_sound in myset)

输出:

True False

相关问题 更多 >