无序查找

从最简单的有序集合列表list中查找数据,并返回数据在列表中的位置:

"""定义一个查找函数
    参数:list(列表) key(键值)
    返回值:i  key值在列表中的位置
"""
def sequential_search(list, key):
    length = len(list)
    for i in range(length):
        if list[i] == key:
            return i
    else:
        return False


if __name__ == '__main__':
    LIST = [5, 6, 8, 399, 242, 754, 657, 99, 4300, 24422]#列表
    result = sequential_search(LIST, 4300) #调用函数
    print('key值所在列表中的位置序列是:',result)

测试结果:

key值所在列表中的位置序列是: 8


Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_41853536/article/details/80075465