Skip to main content
  1. About
  2. For Teams
Asked
Viewed 602 times
0

I had a 2D array where every row has 2 elements:

R3 = [
    [[0, 4, 4, ...]
    [[0, 0, 0, ...]
    [[4, 0, 0, ...]
]

And this is the position of elements of the 2D array.

whereR3 = [
    [0, 1],
    [0, 2],
    [1, 4],
    [1, 34],
    [2, 0],
    [2, 5],
    [3, 8],
    [3, 9],
    [4, 12],
]

I want to do subtract the second element of a row from the first element, but the bottleneck is getting the value in a certain position from the 2D array. Here's what I've tried:

print(R3[0][1] - R3[0][2])

With this code, I can't calculate through every row and can't do it in a loop.

1
  • This is not an array, this is a list
    juanpa.arrivillaga
    –  juanpa.arrivillaga
    2017-09-03 00:49:06 +00:00
    Commented Sep 3, 2017 at 0:49

3 Answers 3

1

You can easily used nested for loops like this:

for list_ in R3:
        for number in list_:
            print(number - list_[1]) #if you know that every row has array of 2 elements
Sign up to request clarification or add additional context in comments.

1 Comment

@juanpa.arrivillaga is this Right?
1

Python indexes from 0, so you'll need to select positions 0 and 1 instead of 1 and 2. You can do that pretty easily in a for loop like this:

for row in whereR3:
    print(row[0] - row[1])

If you want a new list where each row has been collapsed to row[0] - row[1], you can use a list comprehension:

collapsed_R3 = [row[0] - row[1] for row in whereR3]

When executed, collapsed_R3 will be equal to:

[-1, -2, -3, -33, 2, -3, -5, -6, -8]

And to get a specific row's collapsed value (row 0, for example):

whereR3[0][0] - whereR3[0][1]

Which is equal to -1. The first slice ([0] on both sides) selects the row, and the second slice ([0] and [1]) are selecting the item within the row.

2 Comments

Maybe you didn't understand my question. It is my fault. What I mean is, how can I get a value in certain position(whereR3).
@yeonbinson: Sure, I've added that to my answer.
0
result = [y- x for x,y in R3]
[1, 2, 3, 33, -2, 3, 5, 6, 8]

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.