26 janv. 2022

[Dynamo+=Python] Opérations sur des listes imbriquées





Comment appliquer une fonction sur une liste possédante une multi-imbrication ?


if this article is not in your language, use the Google Translate widget (bottom of page for Mobile version)⬈

Il peut arriver que l'on souhaite restituer au travers d'un nœud Python la même structure que la liste d'entrée.

Voici un exemple avec une fonction récursive appelant une autre fonction (opération à effectuer).

Ici, on convertit une liste de points en liste sphère en gardant la même structure.



import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

def convertPointToSphere(pt):
    return Sphere.ByCenterPointRadius(pt, 1)


def nestedRecursFunc(lst, functoApply):
    newlst = list(lst)[:] # copy input list and convert it (if necessary)
    for idx, elem in enumerate(lst):
        if isinstance(elem, list) and len(elem) > 0:
            newlst[idx] = nestedRecursFunc(lst[idx], functoApply)
        elif isinstance(elem, list) and len(elem) == 0:
            newlst[idx] = []
        else:
            newlst[idx] = functoApply(lst[idx])

    return newlst
    
multi_NestedList = IN[0]

OUT = nestedRecursFunc(multi_NestedList, convertPointToSphere)







Une autre solution avec l'arrivée de Python3 et numpy, cela suppose que votre liste d'entrée est homogène (tableau)






import sys
import clr

clr.AddReference('Python.Included')
import Python.Included as pyInc
path_py3_lib = pyInc.Installer.EmbeddedPythonHome
sys.path.append(path_py3_lib + r'\Lib')
sys.path.append(path_py3_lib + r'\Lib\site-packages')

import numpy as np

data, search_value, replace_value = IN

array_3d = np.array(data).astype(object)
array_3d[array_3d == search_value] = replace_value

OUT = array_3d.tolist()

0 commentaires:

Enregistrer un commentaire