python - 线性搜索 - Python

标签 python

<分区>

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

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

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

我需要搜索“西类牙”——为此我要使用什么代码?

提前致谢

最佳答案

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

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

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

如果您想手动完成(为了练习),您可以这样做:

def inList (l, elem)
   for e in l:
     if e == elem:
       return True
   return False

这将遍历所有列表元素,如果找到您正在寻找的元素,它将返回 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  

关于python - 线性搜索 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889861/

相关文章:

python - 使用迭代器实现 Chop()

python - matplotlib - 斑马条纹图形的背景颜色?

python - 如何在搜索函数中取消 OR 中的 AND?在 Odoo 9

python - 非法指令(核心转储)tensorflow

python - 使用 xlwings 编写 VBA 宏来调用 python 脚本

python - 传递包含 3 个整数的数组的 Python CTypes 结构时中止

python - 属性错误: type object 'sklearn.tree._criterion.array' has no attribute '__reduce_cython__'

python - Dockerfile包含一个写入输出文件的python脚本,但未在容器上创建输出文件

python - 使用python在一台机器(windows server 2008)上允许的最大同时HTTP连接数是多少

python - 使用 Python 进行自动化数据挖掘的建议