简体   繁体   中英

How can I get value from 2d array? - Python

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.

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

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.

result = [y- x for x,y in R3]
[1, 2, 3, 33, -2, 3, 5, 6, 8]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM