eduroam-prg-hf-1-5-62.net.univ-paris-diderot.fr 2025-9-29:13:20:41

This commit is contained in:
oskar
2025-09-29 13:20:41 +02:00
parent f9c22c4b98
commit 3b282d338c

View File

@@ -1,34 +1,32 @@
---
description: |
```python
from collections import defaultdict
from pprint import pprint
tree = lambda: defaultdict(tree) # arbre = dictionnaire contenant un arbre
example = tree() # création de l'arbre
example["A"]["A.1"]
example["A"]["A.2"]["A.2.1"]
example["B"]["B.1"]
def tree_to_dicts(tree): # transformer en vrai dictionnaire
return {key: tree_to_dicts(tree[key]) for key in tree}
pprint(tree_to_dicts(example))
def add_path(tree, path):
for node in path:
tree = tree[node]
add_path(example, ["B", "B.2", "B.2.1"])
add_path(example, "B>B.2>B.2.2".split(">"))
pprint(tree_to_dicts(example))
```
up: [[python tips]]
link: "https://gist.github.com/hrldcpr/2012250"
author: [[harold cooper]]
tags:
- "#s/informatique/langage/python"
---
up::[[python tips]]
link::https://gist.github.com/hrldcpr/2012250
author::[[harold cooper]]
title::"definir des [[structure de données.arbre|arbres]] avec les defaultdicts du module [[python module collections]]"
#s/informatique/langage/python
----
Permet de définir la structure d'[[structure de données.arbre]] de manière simple, grace aux `defaultdicts` (module collections)
# Résumé
```python
from collections import defaultdict
from pprint import pprint
tree = lambda: defaultdict(tree) # arbre = dictionnaire contenant un arbre
example = tree() # création de l'arbre
example["A"]["A.1"]
example["A"]["A.2"]["A.2.1"]
example["B"]["B.1"]
def tree_to_dicts(tree): # transformer en vrai dictionnaire
return {key: tree_to_dicts(tree[key]) for key in tree}
pprint(tree_to_dicts(example))
def add_path(tree, path):
for node in path:
tree = tree[node]
add_path(example, ["B", "B.2", "B.2.1"])
add_path(example, "B>B.2>B.2.2".split(">"))
pprint(tree_to_dicts(example))
```
# Définition
```python