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

时间:2016-07-13 09:34:08

标签: python list dictionary

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

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

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

Todo要填什么?

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"}]

如果您注意到sublist2的sublist1引用。这就是原因

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

{'没什么':“注意这个”},{'没有':“注意这个”}

我尝试了以下

Inserting values into specific locations in a list in Python

How to get item's position in a list?

1 个答案:

答案 0 :(得分:2)

除了使用递归之外,您只需查看第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']]