Julia. Exercice : créer un dictionnaire à partir d'une liste de listes.
par
, 15/05/2021 à 12h43 (5170 Affichages)
Question posée sur le forum Python : https://www.developpez.net/forums/d2.../#post11723255
@THOMAS nous donne :
ListNotes = [['Mathématiques', '12'], ['Mathématiques', '9'], ['Mathématiques', '15'], ['Informatique', '17'], ['Physique', '11'], ['Physique', '8'], ['Chimie', '16'], ['Chimie', '10']]
On doit transformer ListNotes en dictionnaire et calculer la moyenne.
Solution Julia
Le travail ne présente pas de difficulté majeure si l'on connaît les fonctions push!, haskey, pairs et mean.
Il faut commencer par mettre cette liste de listes au format Julia (" au lieu de ' et entier au lieu de texte pour les notes).
Code Julia : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 using Statistics function main() ListNotes = [["Mathématiques", 12], ["Mathématiques", 9], ["Mathématiques", 15], ["Informatique", 17], ["Physique", 11], ["Physique", 8], ["Chimie", 16], ["Chimie", 10]] notes = Dict{String, Vector{Int64}}() moyennes = Dict{String, Float64}() for item in ListNotes key = item[1] value = item[2] if haskey(notes, key) push!(notes[key], value) # push dans un array else push!(notes, key => [ value ]) # push dans un dict end end for (key, value) in pairs(notes) push!(moyennes, key => mean(value)) end @show notes @show moyennes end @time main() #= notes = Dict("Informatique" => [17], "Mathématiques" => [12, 9, 15], "Physique" => [11, 8], "Chimie" => [16, 10]) moyennes = Dict("Informatique" => 17.0, "Mathématiques" => 12.0, "Physique" => 9.5, "Chimie" => 13.0) 0.000845 seconds (296 allocations: 17.109 KiB) =#
Licence Creative Commons Attribution 2.0 Belgique