簡體   English   中英

使用遞歸,計算列表中相同元素的數量並將其收集到字典中

[英]Using recursion, count the number of identical elements in the list and collect this in a dictionary

請幫助實現以下功能:

給定一個字符串和列表的列表,其中也可能包含字符串和列表等。您的工作是將這些字符串收集到一個字典中,其中 key 是字符串,value 是這些列表中該字符串出現的次數。

def count_strings(data: list, pos=None, result: dict = None) -> dict:
    """

    :param data: given list of lists
    :param pos: figure out how to use it
    :param result: figure out how to use it
    :return: dict of given symbols and their count
    """

我的嘗試:

if result is None and pos is None:
    result = {}
    pos = 0
if pos > len(data):
    return result
if isinstance(data[pos], str):
    return count_strings(data, pos + 1, result)
elif isinstance(data, list):
    return count_strings(data, 0, result)

輸出應該是這樣的:

    print(count_strings([[], ["J", "*", "W", "f"], ["j", "g", "*"], ["j", "8", "5", "6", "*"], ["*", "*", "A", "8"]]))
    # {'J': 1, '*': 5, 'W': 1, 'f': 1, 'j': 2, 'g': 1, '8': 2, '5': 1, '6': 1, 'A': 1}
    print(count_strings([[], [], [], [], ["h", "h", "m"], [], ["m", "m", "M", "m"]]))  # {'h': 2, 'm': 4, 'M': 1}
    print(count_strings([]))  # {}
    print(count_strings([['a'], 'b', ['a', ['b']]]))  # {'a': 2, 'b': 2}

您獲得的模板並沒有促進最佳實踐(請參閱改變參數的 Python 函數的正確樣式),但忽略這一點,您的代碼存在以下問題:

  • if pos > len(data) :這會錯過這兩個相等的情況,在這種情況下,您還應該輸入if
  • 您的代碼不會使用實際計數更新字典。 特別是當檢查的值是字符串時應該發生這種情況
  • 列表數據類型的測試使用了錯誤的值:您需要測試data[pos]是一個列表,而不是data
  • 當值是列表時,您應該使用該子列表進行遞歸,因此使用data[pos]
  • 當值為列表時,您仍應處理列表的其余部分。

這是一個更正:

def count_strings(data: list, pos=None, result: dict = None) -> dict:
    if result is None and pos is None:
        result = {}
        pos = 0
    if pos < len(data):  # pos should not be equal to len when accessing data[pos]:
        if isinstance(data[pos], str):
            result[data[pos]] = result.get(data[pos], 0) + 1  # increment count
        elif isinstance(data[pos], list):
            count_strings(data[pos], 0, result)  # process nested list
        count_strings(data, pos + 1, result)  # process the remaining entries
    return result

替代函數簽名

如果函數不需要將要變異的result參數,也不需要pos參數,那就更好了。 雖然您不是在尋找改變您獲得的模板的解決方案,但我仍然更喜歡在此處包含替代方案。

這里實際上有兩個問題需要解決:

  • 以遞歸方式迭代嵌套值,以及
  • 在字典中收集字符串頻率

這兩者可以在單獨的函數中解決。 在不使用庫的情況下,您可以按如下方式執行此操作:

def deepvalues(data):
    if isinstance(data, list):
        for item in data:
            yield from deepvalues(item)  # recursion
    else:
        yield data

def count_strings(data: list) -> dict:
    result = {}
    for value in deepvalues(data):
        result[value] = result.get(value, 0) + 1
    return result

暫無
暫無

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

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