我是新手,刚刚开始学习 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