0

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)
X.J
  • 11
  • 1
  • It doesn't need to convert your lists to set in the same part. Code 2 is better. – Heyran.rs Feb 14 '19 at 13:14
  • Right now, the question is a bit unclear. What do you mean with subtraction? Is the result an array too, or do you subtract all pairs? Do you really mean the vector `g`? Then what are `width` and `height`? – Philipp F Feb 14 '19 at 13:15
  • @Heyran.rs I need to know the length of not repeated data, so, in my case, this convert is necessary. Thx – X.J Feb 14 '19 at 13:39
  • @PhilippF I have simplified my case, but it is still a little unclear, sorry for that. In my case, every element with a **width** and a **length** has a data **g**. I want to subtract data **g** with minimal **length** from elements with other(larger) lengths for elements with same widths. I do not know what do you mean result is an array? – X.J Feb 14 '19 at 13:45

0 Answers0