I am the new for python. I try to process data (g in following) using difference method, that subtracts one array from others. I have the following codes. The difference between code 1 and code 2 is: code 1 preallocates a space for list, and in the loop replace every value. Code 2 only defines an empty list at first, and appends data to defined list in loop. The results are the same. However, I'm not familiar with python and do not know which is good. Could someone give me an advice? or a more developed modification about this code?
BR XJ
#Same part:
g = range(1,12)
width = [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3]
length = [1, 2, 3, 1, 2, 3, 1, 2, 3]
width = set(width)
length = set(width)
nr_w = len(width)
nr_l = len(length)
#different parts:
# %%
#Code 1:
i = 0
g_new_1 = [0]*nr_w*(nr_l-1) # preallocating
for i_w in range(nr_w):
for i_l in range(nr_l):
if i_l != 0:
g_new_1[i] = g[i_w*nr_l+i_l] - g[i_w*nr_w]
i=i+1
# %%
#Code 2:
g_new_2 = []
for i_w in range(nr_w):
for i_l in range(nr_l):
if i_l != 0:
g_new_2.append( g[i_w*nr_l+i_l] - g[i_w*nr_w] )
print(g_new_1 == g_new_2)