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
假设你知道线性搜索算法,我想你在比较字符串而不是整数时有问题。(如果没有,请使用this)
如果您想按字典顺序比较字符串,Python中的Boolean运算符可以为您完成这项工作。从这个意义上说,整数和字符串的代码不会有什么不同。希望这有助于您编写它,因为我不想直接给您代码。在
您可以阅读here了解更多详细信息。在
如果您想知道“西班牙”是否在列表中,您可以:
有类似的内置函数来查找它的索引等
如果你想手动操作(为了练习),你可以:
^{pr2}$这将遍历所有列表元素,如果找到您要查找的元素,它将返回
True
,如果没有遇到您要查找的元素,则返回False
如果还关心元素的索引,可以执行以下操作:
相关问题 更多 >
编程相关推荐