繁体   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