Python搜索2d数组并返回if found和index found

2024-09-30 02:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维数组,它可能包含也可能不包含数据。首先,我要搜索包含特定数据的索引,如果为true,则更新数组中的数据

到目前为止,我已经成功地搜索了数组,如果找到了索引,就返回true或false语句。但我还需要返回索引值,以便修改和更新数组中的数据

from itertools import chain
self.asset= [[]]

def findIn2dArray(self, arr, value):
    return value in chain.from_iterable(arr)

if self.findIn2dArray(self.asset, element.get("asset")):
     print("found updating")
     self.asset[???, 1] = new updated value

我知道哪些列需要更改,但我不知道数据的索引位置,希望这是有意义的。如果findIn2dArray函数也能返回索引号就好了,谢谢


Tags: 数据fromimportselffalsetruechainvalue
1条回答
网友
1楼 · 发布于 2024-09-30 02:30:09

不要压平二维列表。使用带有enumerate()的嵌套循环,这样就可以获得索引

def find_in_2d(lists, value):
    for i, l in enumerate(lists):
        for j, item in enumerate(l):
            if item == value:
                return i, j
    return None, None

i, j = find_in_2d(assets, element.get("asset")
if i is not None:
    print("found updating")
    asset[i][j] = new_value

相关问题 更多 >

    热门问题