非ニシキヘビアプローチに従うのは簡単です。
listCountries = ['France', 'Spain', 'United Kingdom', 'Italy', 'Portugal', 'Ireland', 'Poland', 'Norway']
i=0
l = len(listCountries)
while i<l:
if listCountries[i] == "Spain":
print "Spain found at index", i
break;
else:
i=i+1
また、この1
for j in range(len(listCountries)):
if listCountries[j] == "Spain":
print "Spain found at index", j
else:
continue
確かに、あなたはあなたのために全力を尽くしますコードの下
def look_for(c, data):
for j in range(len(data)):
if data[j] == c:
return c+" found at index "+str(j)
else:
continue
return c+" not found"
#print look_for("Spain", listCountries) => will return Spain found at index 1
#print look_for("USSR", listCountries) => USSR not found
#print look_for("Finland", listCountries) => Finland not found
、このような関数の内部スニペットの上にラップすることができます -
print listCountries.index("Spain")
))
なぜ整数の線形検索がそれほど多くなるのでしょうか?文字列、国の線形検索とは異なります...? –
私がプログラミングに非常に新しいと言ったように、配列が整数か文字か文言かどうかによって異なるコードを使用すると仮定しました。 – ladolcevita
よくあるPythonは動的な言語です。つまり、何かをリストに入れることができます。したがって、整数リストのために働くアルゴリズムである多くの*(すべてではない)では、馬や車のリストのためにも動作します。 –