在Python中搜索列表中的值

在Python中搜索列表中的值,python,while-loop,Python,While Loop,我正在使用Python在列表中搜索输入名称的位置。我使用二进制搜索:将输入的名称与列表的中间值进行比较,如果不匹配,则在前半部分列表中搜索,然后在后半部分列表中搜索。 当我运行下面的脚本时,IDE没有显示任何内容。请帮我复习一下: def search_for_name(name, list): midValue = list[int(len(list)/2)] x = 0 if name == midValue: x = int(len(list)/2) retur

我正在使用Python在列表中搜索输入名称的位置。我使用二进制搜索:将输入的名称与列表的中间值进行比较,如果不匹配,则在前半部分列表中搜索,然后在后半部分列表中搜索。 当我运行下面的脚本时,IDE没有显示任何内容。请帮我复习一下:

def search_for_name(name, list):
  midValue = list[int(len(list)/2)]
  x = 0
  if name == midValue:
    x = int(len(list)/2)
    return x
  elif name < midValue:
    while x < int(len(list))/2:
      if list[x] == name:
        return x
      else:
        x += 1
  else:
    x = int(len(list)/2)
    while x <= int(len(list)):
      if list[x] == name:
        return x
      else:
        x += 1
  print('The name you want to search exists in our list. Its position is {}'.format(x))
def搜索名称(名称、列表):
中值=列表[int(len(list)/2]
x=0
如果名称==中值:
x=int(len(列表)/2)
返回x
elif名称<中值:
当x当x从函数返回找到的值时,这意味着永远不会调用
print
语句。相反,请使用返回的值,然后打印:

def search_for_name(name, list):
    ...

pos = search_for_name('matt', ['a', 'b', 'matt', 'x', 'y', 'z'])

if pos is None:
    print("Name was not found")
else:
    print('The name you want to search exists in our list. Its position is {}'.format(pos))

您在哪里实际使用
搜索\u name
功能?为什么会显示任何内容?这只是一个函数定义。你的列表是有序的吗?如果不是,二进制搜索就没有多大意义。但是它包含一个打印@这能回答你的问题吗
f“它的位置是{pos}。”
只要你是在3.6上,肯定!