gpt4 book ai didi

python - 用不同列表中的项目递归替换列表中的项目

转载 作者:行者123 更新时间:2023-12-01 03:50:17 25 4
gpt4 key购买 nike

我已经通过递归实现了完全相同的功能,我还想要一个不带递归的版本,因为 Python 有递归限制并且共享数据时存在问题。

sublist2 = [{'nothing': "Notice This"}]
sublist1 = [{'include':[sublist2]}]

mainlist = [{'nothing': 1}, {'include':[sublist1, sublist2]},
{'nothing': 2}, {'include':[sublist2]}]

待办事项中要填写什么?

for i in mainlist:
if 'nothing' in i:
# Do nothing
else if 'include' in i:
# Todo
# Append the contents of the list mentioned recursively
# in it's own place without disrupting the flow

运行后的预期结果

mainlist = [{'nothing': 1}, 
{'nothing': "Notice This"}, {'nothing': "Notice This"},
{'nothing':2},
{'nothing': "Notice This"}]

如果您注意到 sublist1 引用了 sublist2。原来是这个原因

{'include':[sublist1, sublist2]} 替换为

{'nothing':"注意这一点"}, {'nothing':"注意这一点"}

我尝试过以下方法

Inserting values into specific locations in a list in Python

How to get item's position in a list?

最佳答案

不使用递归,您只需查看第 n 个元素并就地更改它,直到它不需要任何进一步处理。

sublist2 = [{'nothing': "Notice This"}]
sublist1 = [{'include':[sublist2]}]

mainlist = [{'nothing': 1}, {'include':[sublist1, sublist2]},
{'nothing': 2}, {'include':[sublist2]}]

index = 0
while index < len(mainlist):
if 'nothing' in mainlist[index]:
index += 1
elif 'include' in mainlist[index]:
# replace the 'include' entries with their corresponding list
mainlist[index:index+1] = mainlist[index]['include']
elif isinstance(mainlist[index], list):
# if an entry is a list, replace it with its entries
mainlist[index:index+1] = mainlist[index]

注意分配给条目l[0]和分配给切片l[0:1]之间的区别

>>> l = [1, 2, 3, 4]
>>> l[3] = ['a', 'b', 'c']
>>> l
[1, 2, 3, ['a', 'b', 'c']]
>>> l[0:1] = ['x', 'y', 'z']
>>> l
>>> ['x', 'y', 'z', 2, 3, ['a', 'b', 'c']]

关于python - 用不同列表中的项目递归替换列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38347827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com