0
新手一般在此處進行編程。我有一個沒有數字鍵的空字典(在這種情況下不是= 3)。我試圖生成一個列表,這些列表將被添加到循環中的字典中,但是在每個循環中,其他鍵將被覆蓋。見我以下嘗試:試圖將列表的列表添加到for循環中的空字典中,但是在每次迭代中條目都被完全覆蓋
#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)
這是當我檢查進展的輸出:
{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]]}
對於上下文中,這是產生具有相同纖維元件內的一個隨機分佈的ABAQUS網格文件矩陣。
編輯:上下文
使用copy.deepcopy工作
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)
輸出:
{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]]}
請參閱https://stackoverflow.com/q/2612802/8586227 –
謝謝。 copy.deepcopy爲我工作 – Aedan