【发布时间】: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