Py学习  »  Python

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

Super Sonic • 5 年前 • 1483 次点击  

我有一个二维数组,可能包含数据,也可能不包含数据。首先我要搜索包含特定数据的索引,如果为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函数也返回索引号,那就太好了,谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52196
 
1483 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Barmar
Reply   •   1 楼
Barmar    5 年前

不要压平二维列表。使用嵌套循环 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