簡體   English   中英

如何在嵌套列表中搜索字符串

[英]How to search for strings within nested lists

我正在做的作業的問題之一是,在由“超短篇小說及其作者”組成的嵌套列表中查找,以查找用戶輸入的字符串。 不確定如何執行此操作,如果有人想進一步澄清,請參見下面的作業簡介。 還有更多我不確定的問題,例如“查找某個作者的所有故事”。 一些解釋,或指向正確的方向,我將不勝感激:)

list = []
mylist = [['a','b','c'],['d','e','f']]

string = input("String?")

if string in [elem for sublist in mylist for elem in sublist] == True:
    list.append(elem)

這只是我嘗試過的一個示例,上面的列表與我實際用於該問題的列表足夠相似。 我目前剛剛經歷了遍歷嵌套列表並將數學項添加到另一個列表的不同方法。 上面的代碼只是我在此過程中嘗試過的一個示例。

""" the image above states that the data is in the
form of an list of sublists, with each sublist containing
two strings
"""

stories = [
    ['story string 1', 'author string 1'],
    ['story string 2', 'author string 2']
]


""" find stories that contain a given string
"""
stories_with_substring = []
substring = 'some string'  # search string

for story, author in stories:
    # if the substring is not in the story, a ValueError is raised
    try:
        story.index(substring)
        stories_with_substring.append((story, author))
    except ValueError:
        continue

""" find stories by a given author
"""
stories_by_author = []
target_author = 'first last'

for story, author in stories:
    if author == target_author:
        stories_by_author.append((story, author))

這條線在這里

for story, author in stories:

“解壓”陣列。 相當於

for pair in stories:
    story = pair[0]
    author = pair[1]

或更進一步:

i = 0
while i < len(stories):
    pair = stories[i]
    story = pair[0]
    author = pair[1]

我確定您可以看到在處理包含列表/元組的列表時這很有用。

如果您希望搜索不區分大小寫,則可能需要在某些字符串上調用.lower()

您可以在這里做一些事情。 您的示例說明了列表理解的使用,因此讓我們集中討論此問題的其他方面。

遞歸

您可以定義一個遍歷頂層列表中所有項目的函數。 假設您確定所有項目都是字符串或更多列表,則可以使用type()檢查每個項目是另一個列表還是字符串。 如果是字符串,請進行搜索-如果是列表,請調用函數。 讓我們看一個例子。 請注意,我們永遠不要使用名為liststring變量-這些是核心值類型,我們也不想意外覆蓋它們!

mylist = [['a','b','c'],['d','e','f']]

def find_nested_items(my_list, my_input):
    results = []
    for i in mylist:
        if type(i) == list:
            items = find_nested_items(i, my_input)
            results += items
        elif my_input in i:
            results.append(i)
    return results

我們在這里做一些事情:

  1. 創建一個名為results的空列表
  2. 遍歷my_list的頂級項目
  3. 如果其中一項是另一個列表,我們將調用函數本身-在某個時候,這將觸發條件,即某項不是列表,並最終從中返回結果。 目前,我們假設返回的結果是正確的,因此我們將這些結果連接到頂級results列表中
  4. 如果該項目不是列表,則只需檢查輸入是否存在,如果存在,則將其添加到結果列表中

這種遞歸通常非常安全,因為它固有地受我們的數據結構限制。 除非數據結構本身是無限深的,否則它不會永遠運行。

發電機

接下來,讓我們看一下python 3:generators的一個更酷的功能。 目前,我們正在一次性完成所有收集結果的工作。 如果以后要遍歷這些結果,則需要分別遍歷它們。

代替這樣做,我們可以定義一個生成器。 實際上,它的工作原理幾乎相同,但是與其在一個循環中收集結果然后在第二秒中使用它們,不如在一個循環中收集並使用所有結果。 生成器“產生”一個值,然后停止直到下次調用它為止。 讓我們修改示例以使其成為生成器:

mylist = [['a','b','c'],['d','e','f']]

def find_nested_items(my_list, my_input):
    for i in mylist:
        if type(i) == list:
            yield from find_nested_items(i, my_input)
        elif my_input in i:
            yield i

您會發現此版本短很多。 無需將項目保存在臨時列表中-每個項目都是“已產生”的,這意味着它會直接傳遞給調用方以立即使用,並且調用方將停止生成器,直到需要下一個值為止。

yield from基本上執行相同的遞歸,它只是在生成器中設置生成器,以將這些嵌套項返回到鏈上並返回給調用者。

這些是一些不錯的技巧,請嘗試一下!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM