0

リストのプログラム指定レベルに要素を挿入するにはどうすればよいですか? 私の解決策はあまりPythonicではありません:

def listInsertDepth(l,e,i,lvl): # Insert element e into list l at depth lvl using list of indices i
    if lvl < 0: # That is, if your depth level is invalid
        return l
    else:
        assert len(i) == lvl+1 # One index for every level, plus for the actual insertion
        s = l # A copy for tampering with
        for index in range(lvl):
            s = s[i[index]]
        s.insert(i[-1],e)
        return listInsertDepth(l,s,i[:-1],lvl-1) 
4

1 に答える 1

2

一連のインデックスを指定すると、最後のものを除いてすべてをループして、ネストされた構造を親リストにトラバースして挿入することができます。

listInsertAtDepth(lst, value, indices):
    parent = lst
    for index in indices[:-1]:
        parent = parent[index]
    parent.insert(indices[-1], value)

try,コンボを追加して、exceptインデックスが間違っていることを検出できます。

listInsertAtDepth(lst, value, indices):
    parent = lst
    try:
        for index in indices[:-1]:
            parent = parent[index]
        parent.insert(indices[-1], value)
     except IndexError:
        return None

でも個人的には、飲み込んで捨てられるよりも例外が欲しいです。

lstインプレースで変更されるため、関数から戻るべきではないことに注意してください。.append()リストをインプレースで変更するや などのPython stdlib メソッド.extend()も何も返しません。

于 2013-01-15T18:08:09.847 に答える