线性搜索Python

2024-10-03 23:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新手,刚刚开始学习Python。我在课程中的第一个作业要求我对一个国家的列表进行线性搜索(我知道线性搜索很糟糕,但这只是为了练习:),我找不到不涉及整数的简单线性搜索的代码。在

我假设第一步是创建一个数组,它将是:

listCountries = ['France', 'Spain', 'United Kingdom', 'Italy', 'Portugal', 'Ireland', 'Poland', 'Norway']

我需要搜索“西班牙”-我会用什么代码?在

提前谢谢


Tags: 代码列表作业线性整数数组国家课程
3条回答

假设你知道线性搜索算法,我想你在比较字符串而不是整数时有问题。(如果没有,请使用this

如果您想按字典顺序比较字符串,Python中的Boolean运算符可以为您完成这项工作。从这个意义上说,整数和字符串的代码不会有什么不同。希望这有助于您编写它,因为我不想直接给您代码。在

您可以阅读here了解更多详细信息。在

如果您想知道“西班牙”是否在列表中,您可以:

'Spain' in listCountries ## returns true if the string 'Spain' is an element of listCountries

有类似的内置函数来查找它的索引等

如果你想手动操作(为了练习),你可以:

^{pr2}$

这将遍历所有列表元素,如果找到您要查找的元素,它将返回True,如果没有遇到您要查找的元素,则返回False

如果还关心元素的索引,可以执行以下操作:

def whereInList (l,elem): ## return the index of desired element, if not in list return None
  for i,e in enumerate(l):
    if e == elem:
      return i
  return None  
countries = ["France", "Spain", "United Kingdom", "Italy", "Portugal", "Ireland", "Poland", "Norway"]

countrie_to_search = 

for index, item in enumerate(countries, 0):
    print("index: {} country: {}".format(index, item))
    if item = countrie_to_search:
        # we have a match, do what you want

相关问题 更多 >