MAJ
MAJ

Reputation: 497

How to append in multidimensional arrays using python?

I have two 1-D arrays:

tminus = [219 220 225 226 227 332]
tplus = [221 222 227 228 229 334]

And a 2-D array:

t = [[222 224 228 244],[264 280 283 255 346]]

How do I append t for the values that are in between tminus and tplus? I am trying to keep t as the 2-D array. I tried:

time = []
for k in range(len(tminus)):
    for i in range(len(t)):
        for j in range(len(t[i])):
            if tminus[k] <= t[j] <= tplus[k]:
                time.append(t[j])
print time

But, all I get is the empty list.

Any suggestions?

Upvotes: 0

Views: 1520

Answers (2)

DerMann
DerMann

Reputation: 243

I am not really sure if this is what you are looking for but from my understanding this should solve the problem.

index = 0
for i in range(0,len(t)):
    for j in range(0,len(t[index])):
        if max(tminus) <= t[i][j] <= min(tplus):
            time.append(t[i][j])
    index +=1
return time

Upvotes: 0

Moeez Muhammad
Moeez Muhammad

Reputation: 56

In this line:

if tminus[k] <= t[j] <= tplus[k]:

Note that you call t[j], which will find the jth element inside of t. However, t[j] will always be a list, as t is a 2D array.

To iterate over the sublists(t[i]) inside of t, use

t[i][j]

This gets the jth element in the ith element in t.

For example, if i is 0, and j is also 0, t[j] would return [222, 224, 228, 244], and you can't compare an int to a list. Instead, t[i][j] would return 222, which is what you were aiming for.

Because you also want the shape of t to stay the same, create a temporary variable (appendList), append values to that, then append the whole list to t.

However, with your current code, it will create unnecessary lists, as it will create one for every element in tminus. To avoid this, you can switch the order of the for loops, so that it only creates appendList. Also, this can cause a single number to be appended multiple times, so we pass it into set() to remove duplicates, and then pass it into list() to turn it into a list again.

Updated code:

tminus = [219, 220, 225, 226, 227, 332]
tplus = [221, 222, 227, 228, 229, 334]
t = [[222, 224, 228, 244],[264, 280, 283, 255, 346]]

time = []
for i in range(len(t)): # Iterate over t
    appendList = [] # Stores values to be appended to time
    for j in range(len(t[i])): # Iterate over the sublists in t
        for k in range(len(tminus)): # Iterate over tminus
            if tminus[k] <= t[i][j] <= tplus[k]: # Check value
                appendList.append(t[i][j]) # Append value to appendList
    appendList = list(set(appendList)) # Remove duplicates
    time.append(appendList) # Append entire list to time
print(time)

This gives the result: [[228, 222], []]

Caveats:
- If t has repeating elements, only one of them will stay
- Order is lost when passing into set()

Upvotes: 1

Related Questions