Novice avec programmation en général ici. J'ai un dictionnaire vide sans nombre de clés, (où non dans ce cas = 3). J'essaie de générer une liste de listes qui seront ajoutées au dictionnaire dans une boucle, mais sur chaque boucle les autres touches sont écrasées. Voir ma tentative ci-dessous:Essayer d'ajouter des listes de listes à un dictionnaire vide dans une boucle for, mais les entrées sont complètement écrasées à chaque itération
#generating dictionary for all fibres with number n
fibre = {i : {}for i in range(no)}
#generating empty fibre of size n_f
fibre_e = [[[] for i in range(n_f)] for j in range(n_f)]
rand_r = [[] for a in range(no)]
rand_c = [[] for a in range(no)]
#generating fibre element from random corner elements
for a in range(no):
# choosing a random corner element
fibre[a] = fibre_e
rand_r[a] = randrange(len(all_e))
rand_c[a] = randrange(len(all_e))
for i in range(n_f):
e1_fibre=all_e[rand_r[a]][rand_c[a]]
#move to upper row
rand_r[a] += 1
for j in range(n_f):
fibre_e[i][j] = e1_fibre
e1_fibre += 1
print(fibre)
Ceci est la sortie lorsque j'ai vérifié la progression:
{0: [[57, 58], [66, 67]], 1: {}, 2: {}}
{0: [[33, 34], [42, 43]], 1: [[33, 34], [42, 43]], 2: {}}
{0: [[29, 30], [38, 39]], 1: [[29, 30], [38, 39]], 2: [[29, 30], [38, 39]]}
Pour le contexte, cela est de générer un fichier de maillage Abaqus avec une distribution aléatoire des éléments de fibre identiques dans un matrice.
modifier: contexte
L'utilisation copy.deepcopy a travaillé
for a in range(no):
# choosing a random corner element
rand_r[a] = randrange(len(all_e))
rand_c[a] = randrange(len(all_e))
for i in range(n_f):
e1_fibre=all_e[rand_r[a]][rand_c[a]]
#move to upper row
rand_r[a] += 1
for j in range(n_f):
fibre_e[i][j] = e1_fibre
e1_fibre += 1
fibre[a] = copy.deepcopy(fibre_e)
print(fibre)
Sortie:
{0: [[68, 69], [77, 78]], 1: {}, 2: {}}
{0: [[68, 69], [77, 78]], 1: [[6, 7], [15, 16]], 2: {}}
{0: [[68, 69], [77, 78]], 1: [[6, 7], [15, 16]], 2: [[28, 29], [37, 38]]}
Voir https://stackoverflow.com/q/2612802/8586227 –
merci. copy.deepcopy a fonctionné pour moi – Aedan