简体   繁体   English

我如何从二维数组中获取价值? -Python

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

I had a 2D array where every row has 2 elements: 我有一个2D数组,其中每一行都有2个元素:

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

And this is the position of elements of the 2D array. 这是2D数组元素的位置。

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. 我想从第一个元素中减去行的第二个元素,但瓶颈是从2D数组中的某个位置获取值。 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循环:

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: Python从0开始索引,因此您需要选择位置0和1而不是1和2。您可以在for循环中轻松地做到这一点,如下所示:

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: 如果您想要一个新的列表,其中的每一行都已折叠为row[0] - row[1] ,则可以使用列表推导:

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

When executed, collapsed_R3 will be equal to: 执行后, collapsed_R3将等于:

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

And to get a specific row's collapsed value (row 0, for example): 并获取特定行的折叠值(例如,行0):

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

Which is equal to -1 . 等于-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. 第一个切片(两侧均为[0] )选择该行,第二个切片( [0][1] )选择该行中的项目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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