当迭代 Python 3 中的元素列表时,如何“隔离”感兴趣的元素之间的内容?
我有一个清单:
list = ["<h1> question 1", "question 1 content", "question 1 more content", "<h1> answer 1", "answer 1 content", "answer 1 more content", "<h1> question 2", "question 2 content", "<h> answer 2", "answer 2 content"]
Run Code Online (Sandbox Code Playgroud)
在此列表中,有些元素带有标签 < h >,而其他元素则没有。这个想法是,具有此标签的元素是“标题”,并且直到下一个标签的后续元素是其内容。
如何将属于 header 的列表元素连接起来以获得两个大小相等的列表:
headers = ["<h1> question 1", "<h1> answer 1", "<h1> question 2", "<h> answer 2"]
content = ["question 1 content question 1 more content", "answer 1 content answer 1 more content", "question 2 content", "answer …Run Code Online (Sandbox Code Playgroud) 我有一个只有几个单词的字符串列表,我需要搜索两个关键字,然后返回包含这两个关键字的字符串。
我试图遍历字符串,但无法这样做。我尝试了.find()函数,但在字符串列表上未成功。
假设我们有一个列表:
list = ["The man walked the dog", "The lady walked the dog","Dogs
are cool", "Cats are interesting creatures", "Cats and Dogs was an
interesting movie", "The man has a brown dog"]
Run Code Online (Sandbox Code Playgroud)
我想遍历字符串列表,并在包含单词“ man”和“ dog”的新列表中返回字符串。理想情况下,要获得以下内容:
list_new = ["The man walked the dog", "The man has a brown dog"]
Run Code Online (Sandbox Code Playgroud)