【问题标题】:How to use recursion in heterogenous list and dict如何在异构列表和字典中使用递归
【发布时间】:2021-09-23 18:15:26
【问题描述】:

我在 python 中学习recursion 并解决了一些常见问题,如阶乘、遍历嵌套列表等。 在解决此类问题时,我提出了这个挑战,您必须使用递归遍历异构输入(包含单个 str 元素、嵌套列表、字典等的输入)。

因此挑战涉及遍历此输入中的所有值并将指定值替换为另一个值。

此处使用的输入如下所示:

input = ['a', 'b', {'1':{'o':'a'}}, 'c', 'd', {'T': 'b', 'K': [1, 'a', 3, {'S':{'Z':'t'},'R':{'3':'a'}}, {'key':[66,'a',88]}, ['a', 'c']]}, ['a'], 3, 'r', 'a']

输入是一个list,它本身包含lists 和dicts,其中一些列表和字典是嵌套的,并且它们本身也有另一个。

我期望得到的输出是:

# this is the output that should be got at the end, after running the code
['#', 'b', {'1':{'o':'#'}}, 'c', 'd', {'T': 'b', 'K': [1, '#', 3, {'S':{'Z':'t'},'R':{'3':'#'}}, {'key':[66,'#',88]}, ['#', 'c']]}, ['#'], 3, 'r', '#']
# exactly like input but with all 'a' replaced with '#'
# of course we can use treat change the input to string and then use replace() of string module and get the output
# but then this wont be a challenge would it?

正确 = ['a', 'b', 'a', 'c', 'd', 'b', 1, 'a', 3, 't', 'a', 66, 'a ', 88, 'a', 'c', 'a', 3, 'r', 'a']

我写的代码是:

remove = 'a'
replace = 'X'

output = []
def recall(input):
    for item in input:
        if isinstance(item, list):
            recall(item)
        elif isinstance(item, dict):
            for entry in item.values():
                recall(entry)
        else:
            if isinstance(input, dict) and item in input.keys():
                if input[item]==remove:
                    input[item]=replace
                    output.append(input[item])
                else:
                    output.append(input[item])
            else:
                if item==remove:
                    item=replace
                    output.append(item)
                else:
                    output.append(item)
            print(item)

recall(input)
print(output)

这会产生输出:

['X', 'b', 'X', 'c', 'd', 'b', 1, 'X', 3, 't', 'X', 66, 'X', 88, 'X', 'c', 'X', 3, 'r', 'X']
# a single list with all the 'a' replaced but there are no dicts with their key value pairs in it

我无法找到实现所需输出的方法。 难道我做错了什么?或者有什么方法可以通过递归实现所需的输出?

【问题讨论】:

    标签: python list dictionary recursion


    【解决方案1】:

    您将所有值附加到单个全局输出变量,无论它们来自嵌套字典还是列表。相反,您需要让函数返回一个值,以便下一级的函数可以适当地处理它 - 在嵌套层次结构中的正确位置附加一个字典或列表。例如,您可以这样做:

    def replace_values(item, replacement):
        if isinstance(item, list):
            return [replace_values(v, replacement) for v in item]
        elif isinstance(item, dict):
            return {k: replace_values(v, replacement) for k, v in item.items()}
            # Alternatively, in case you need the dict keys to be replaced too:
            # return {replacement.get(k, k): replace_values(v, replacement) for k, v in item.items()}
        else:
            return replacement.get(item, item)
    
    input_list = ['a', 'b', {'1':{'o':'a'}}, 'c', 'd', {'T': 'b', 'K': [1, 'a', 3, {'S':{'Z':'t'},'R':{'3':'a'}}, {'key':[66,'a',88]}, ['a', 'c']]}, ['a'], 3, 'r', 'a']
    print(replace_values(input_list, {"a": "#"}))
    

    请注意,返回值中元素的类型(字典、列表或其他)和排序与输入 item 中的相同。这保留了输入的嵌套结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2020-05-25
      • 2013-12-31
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多