📜  Python|列表或元组的线性搜索

📅  最后修改于: 2022-05-13 01:54:52.529000             🧑  作者: Mango

Python|列表或元组的线性搜索

让我们看一下Python列表和元组的基本线性搜索操作。

一种简单的方法是进行线性搜索,即

  • 从列表最左边的元素开始,将 x 与列表的每个元素一一进行比较。
  • 如果 x 与某个元素匹配,则返回 True。
  • 如果 x 不匹配任何元素,则返回 False。

示例 #1:列表上的线性搜索

# Search function with parameter list name
# and the value to be searched
def search(list,n):
  
    for i in range(len(list)):
        if list[i] == n:
            return True
    return False
  
# list which contains both string and numbers.
list = [1, 2, 'sachin', 4,'Geeks', 6]
  
# Driver Code
n = 'Geeks'
  
if search(list, n):
    print("Found")
else:
    print("Not Found")
输出:
Found

请注意,列表是可变的,但元组不是。

示例 #2:元组中的线性搜索

# Search function with parameter list name
# and the value to be searched
def search(Tuple, n):
  
    for i in range(len(Tuple)):
        if Tuple[i] == n:
            return True
    return False
  
# list which contains both string and numbers.
Tuple= (1, 2, 'sachin', 4, 'Geeks', 6)
  
  
# Driver Code
n = 'Geeks'
  
if search(Tuple, n):
    print("Found")
else:
    print("Not Found")
输出:
Found