python获取元素在数组中的位置

获取元素在数组中的位置

array = [[3, 4, 8, 2, 7, 9],
         [6, 3, 0, 9, 4, 6],
         [5, 3, 8, 7, 9, 9],
         [7, 6, 5, 4, 3, 7],
         [3, 0, 4, 1, 9, 6],
         [4, 6, 3, 6, 7, 7]
]
num = int(input("请输入要查找元素:"))


def get_element_index(array, num):
    place = []
    length = len(array)
    for i in range(length):
        if num in array[i]:
            stops = len(array[i])
            inits = 0
            try:
                element_index = array[i].index(num, inits, stops)
                while element_index or element_index == 0:
                    here = array[i].index(num, inits, stops)
                    place.append((i+1, here+1))
                    inits = here + 1
            except ValueError:
                continue
    if not len(place):
        print("元素不存在")
    else:
        print("元素位置是:", place)
    return place


get_element_index(array,num)

测试输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ye__mo/article/details/123085785