2016-07-13 27 views
1

再帰とまったく同じ機能を実装しました。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参照が気付いた場合。 {: "お知らせこの" '何もない'}、{ '何': "お知らせこの"}

によって置き換えられます。それは

{[sublist1、sublist2は] 'を含む'}理由です私は、次の

代わりに再帰を使用しての、あなただけのn番目の要素を見て、それを変更

Inserting values into specific locations in a list in Python

How to get item's position in a list?

+1

に割り当てることの違いを私は混乱しています。あなたはこれを再帰的にやりたいのですか?あなたの最初のパラグラフとタイトルは互いに矛盾します。 – Jokab

+0

Pythonに再帰制限(デフォルトは1000)があるのは間違いありませんが、データ構造がそれを破っている場合は、データに深刻な問題があると言います。 –

+0

@ Jokab私はリストが再帰的に設定されるべきであることを意味しました。私は再帰を使用したくありません。 –

答えて

2

を試してみましたそれ以上の処理を必要としなくなるまで所定の位置に保持する。

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']] 
関連する問題