[Evans] There are many other ways to define find_element.
I'm going to show you 1 way that takes advantage of another built-in list operation
that we haven't introduced yet but that makes it much easier to write find_element.
The operation is called index.
The index method is invoked on a list.
You pass in a value, and the output in index is the position that that value exists in the list.
So the built-in index almost solves find_element exactly the way we want.
The difference is when we invoke index on a list that doesn't contain the value we pass in.
Index doesn't return -1. What it does is gives us an error.
So let's look at what happens in the Python interpreter.
I'll define a variable p and give it the value of the list 0, 1, 2.
If we invoke index on p, passing in 2, we get as the result 2,
which is the position in p where the value 2 occurs.
For the second example we'll add more 2s in the list,
and we see that it always gives us the first one.
So the result returned by p index is the first place in the list where that occurs.
Now we'll try an element that doesn't exist in the list.
What we see is instead of getting -1 as a result we get an error
that the target element that we looked for doesn't appear in the list.
So if we want find_element to have the behavior that's described,
we can't quite do it using index directly.
There are some other list operations that might be very helpful, though.
So to summarize the behavior of the index method,
if the value passed in is in the list, it returns the first position where the value is found.
This is exactly what we wanted for find_element.
The problem is if the value is not found in the list, it produces an error.
There's another list operation that will be useful to allow us to use index to find_element,
and it's useful for many other things, and that's the in word.
We've already seen in being used in the for-loop.
Here we use the same word in, but in this context it means something different.
The syntax is to have a value to the left of the in word followed by the list.
The syntax is a bit strange compared to the other things we've seen in Python.
It doesn't look like a procedure call, but it's very natural in terms of how it corresponds
to how we would say this in English.
If we say something like, "Is 3 in the list?"
we would write that in Python as 3 in p.
So let's see how that works in the interpreter.
Now I'm printing the result of 3 in p.
3 is not in the list, so it prints out False.
If I change this to print the result of 2 in p,
we get the value True.
So to summarize the behavior of the in operator,
if the value is in the list, the output is true.
Otherwise the output is false.
Similarly, we can use not in.
Not in has the opposite meaning of in.
If the value is not in the list, the result of value not in list is true.
If the value is in the list, then the result of value not in list is false.
The value not in list is exactly equivalent to saying not value in list.
The only reason to have the not in is it's more natural to read it this way in English
than having the not between the value and the in.
So now to check that you understand index and in and not in operations,
I want you to try to define the find_element procedure again.
It should have the same exact behavior as the ones we've defined before.
It should give us the position of the element we're searching for if it exists,
and it should give us -1 if it doesn't exist.
But this time instead of using a while loop or a for-loop to define it
see if you can define it using index.
Ci sono molti altri modi per definire 'find_element' .
Vi farò vedere come ci sia un altro modo per avvantaggiarsi di un'altra operazione sulle liste
che ancora non abbiamo introdotto, ma che rende molto più semplice scrivere 'find_element' .
Questo metodo si chiama 'index()' .
Il metodo 'index()' può essere invocato su una lista.
Gli si passa un valore, ed il risultato sarà la posizione di quel valore nella lista.
Questo metodo Python quindi risolve 'find_element' nel modo in cui vorremmo.
La differenza rimane quando il valore passato non è nella lista.
'index()' non ritorna -1, ma ci segnala un errore.
Vediamo cosa succede nell'interprete.
Definisco una variabile 'p' e gli assegno la lista [0,1,2] .
Se si invoca 'index()' per 'p' , passando il valore 2, avremo il risultato 2,
che è la posizione in 'p' dove troviamo il valore '2'.
Per il secondo esempio aggiungiamo più '2' nella lista,
e vediamo che ci darà come risultato comunque il primo.
Quindi il valore ritornato da 'index()' sarà sempre la prima occorrenza che troviamo nella lista.
Adesso proviamo con un elemento che non è nella lista.
Notiamo che invece di ricevere -1 , riceviamo un errore
che dice che l'elemento che stiamo cercando non è nella lista.
Quindi se vogliamo che 'find_element' abbia il comportamento richiesto,
possiamo farlo uando 'index()' direttamente.
Ci sono altri operatori per le liste che potrebbero essere di aiuto.
Per ricapitolare il comportamento di 'index()' ,
se il valore che passiamo è nella lista, il metodo ritorna la posizione della prima occorrenza di quel valore.
Che è esattamente quello che vogliamo da 'find_element' .
Il problema è quando il valore non è presente nella lista, il metodo produce un errore.
C'è quindi un altro metodo che potrebbe tornare utile per permetterci di usare 'index()' ,
e per molte altre cose, si tratta della parola chiave 'in' .
La abbiamo già incontrata nel ciclo 'for' .
Qui vediamo la stessa parola 'in' , ma che significa qualcosa di diverso.
La sintassi prevede di avere un valore alla sinistra della parola 'in' seguito dalla lista.
La sintassi risulta un po' strana dal resto delle cose che abbiamo visto in Python.
Non sembra un richiamo di una procedura, ma è molto naturale per come corrisponde all'ordine logico.
di come lo diremmo in inglese.
Se abbiamo una cosa del tipo : "Is 3 in the list?"
lo scriveremo in Python come '3 in p' .
Vediamo come funziona dell'interprete.
Ora stamperò il risultato di '3 in p' .
3 non è nella lista, quindi stamperà 'False' .
Se cambio in '2 in p' ,
avremo il valore 'True' .
Quindi per ricapitolare il comportamento di 'in' ,
se il valore è nella lista il prodotto è True .
Altrimenti il prodotto è False.
similmente, possiamo usare 'not in' .
'not in' ha significato opposto a 'in' .
Se il valore NON è nella lista, il risultato sarà 'True' .
Se il valore è nella lista, allora il risultato di 'not in list' sarà False.
Il valore di 'not in list' è equivalente a dire "not value in list" .
L'unica ragione per preferire 'not in' è che risulta più naturale in inglese
che avere il 'not' tra il valore e 'in' .
Ora per vedere di aver capito 'index()' e 'in' e 'not' nelle operazioni sulle liste,
Voglio che proviate a definire 'find_element' di nuovo.
Dovrà avere lo stesso identico comportamento di prima.
Dovrà darci la posizione dell'elemento che stiamo cercando, se esiste,
oppure -1 se non esiste nella lista.
Questa volta invece di usare i cicli 'while' o 'for'
utilizziamo 'index()' per definirla.
find_elementを定義する方法は
他にもたくさんあります
組み込まれたリスト操作を活用する方法を
1つ紹介します
これはまだ紹介していませんでしたが
find_elementをはるかに書きやすくするものです
操作はindexと呼ばれています
リスト.index(値)となります
値を渡します indexの出力はリストに存在している
その値の位置になります
indexメソッドを使うことで
望む通りの方法でfind_elementを解決できます
異なることはリストでindexを呼び出す際に
渡す値が含まれていないことです
indexは-1を返しません
行うのはエラーを出すことです
Pythonインタプリタで何が起きるか見てみましょう
リストpに0、1、2の値を代入します
p.index(2)の結果として2を得ます
これは値2が現れるpの位置になります
2つ目の例ではさらに2をリストに追加します
常に1つ目が与えられることが確認できます
indexによって返された結果は
それが現れるリスト内の1つ目の場所になります
ここでリストに存在していない要素を試してみます
結果として-1を得るのではなく
探しているターゲット要素が
リストにはないというエラーが出ることが確認できます
記述されているように
find_elementを作用させたい場合
indexを直接使ってそれを行うことはできません
しかしとても役立つ別のリスト操作があります
indexメソッドの作用をまとめると
渡された値がリストにある場合
値が見つかる1つ目の位置を返します
まさにこれがfind_elementに求めていたものです
リストで値が見つからなかった場合に
エラーが出されることが問題になります
find_elementにインデックスを使用できる
有効な別のリスト操作があります
別のものにも有効的です それはinというワードです
forループで使用されているinをすでに学習しています
ここで同じinを使用していますが
この文中では少し違う意味になります
構文ではinというワードに続く
リストの左辺に値を置きます
構文はPythonで学習してきたものと比較すると
少し変わっています
これは関数の呼び出しには見えませんが
英語で話す感じと似ているという点でとても自然です
Is 3 in the list?のように話したら
Pythonでは3 in pとなります
インタプリタでどのように機能するのか見てみましょう
3 in pの結果を出力します
3はリストにないのでFalseが出力されます
これを2 in pの結果を出力するように変更したら
Trueの値が得られます
in演算子の作用をまとめると
リストに値がある場合の出力はTrueになります
そうでなければFalseが出力されます
同様にnot inを使用できます
not inはinの反対の意味です
値がリストになければ
値 not in リストの結果はTrueになります
値がリストにある場合は
値 not in リストの結果がFalseになります
値 not in リストはリストに値がないと
言っているのとまったく同じことです
not inを使用する唯一の理由は
値とinの間にnotを置くよりも
英語でこのように読む方が自然だからです
それではin、not in操作とindex操作を
理解できているか確認するために
もう一度find_element関数を
定義してみてください
以前定義したものと
まったく同じ作用にしなければなりません
存在すれば検索している要素の位置が
与えられるはずです
存在していなければ-1が与えられます
しかし今回はwhileループやforループを使用して
定義するのではなく
indexを使用して定義できるか確認してください
[Evans] 定义find_element还有很多其他方法。
下面我将展示一种方法,这种方法利用另一个内建列表操作,
我们尚未介绍这个操作,但是这大大简化了find_element的编写。
这个操作叫做索引。
索引方法在列表上被调用。
你传入一个值,索引的输出是那个值存在于列表中的位置。
所以这个内建索引几乎完全按照我们的心意解决了find_element。
不同之处在于,当我们在列表上调用索引,而该列表不包含我们传入的值,
索引不会返回 - 1。而是显示出错。
我们来看看Python解释器中的情况。
我将定义一个变量p并传入列表0,1,2的值。
如果我们在p上调用索引,传入2,我们得到的结果是2,
也就是2这个值在p中的位置。
第二个例子中,我们多加两个2到列表中,
我们看到,它总是显示第一个2。
所以,p索引返回的结果是找到值2的第一个位置。
现在我们将试着传入一个列表中不存在的元素。
我们看到,结果不是 - 1,而是显示出错,
我们要找的目标元素在列表中不存在。
所以,如果我们想让find_element完全按照要求行事,
我们就不能直接使用索引。
但还有其他一些可能很有帮助的列表操作。
总结一下索引方法的功能,
如果传入的值存在于列表中,过程返回找到这个值的第一个位置。
这正是我们想让find_element做的。
问题在于,如果这个值在列表中找不到,过程就会显示出错。
还有一个列表操作可以帮助我们使用索引来编写find_element,
这种方法也对其他很多事情有帮助,那就是单词in
我们已经见过in被使用在for循环中。
这里,我们使用同一个词in,但是在这个语境下,它的意义有所不同。
这个句法是在in的左边放一个值,in后面跟一个列表。
这个句法与我们之前见到的Python语言相比有些奇怪。
它看起来不像一个过程调用,但是,在用英文对这个内容进行表达时,
用它是非常自然的。
如果我们说:“3在列表中吗?”
我们用Python语言写出来就是3 in p。
我们看看解释器中的情况。
现在我打印出3 in p的结果。
3不在列表中,所以打印出来的为假。
如果我把它改成2 in p,
我们得到的值为真。
总结一下in操作的功能,
如果值存在于列表中,输出为真。
反之为假。
类似地,我们可以使用 not in。
Not in正好与in相反。
如果值不存在于列表中,那么not in 列表结果的值为真。
如果这个值存在于列表中,那么not in 列表结果的值为假。
〈value〉not in〈list〉完全等同于 not〈value〉in〈list〉
采用not in的唯一原因是,在英文中,这比把not放在值和in之间
读起来更顺一些,
现在检查一些你是否理解了索引,in和not in等操作。
我想让你试着再次定义find_element过程。
它跟我们之前的定义功能一模一样。
它会给出我们搜索的元素位置,如果该元素存在,
如果不存在,它会显示 - 1
但是这次,不用while循环或for循环
你试试看是否能够使用索引来定义它。
還有很多其他方法能夠定義 find-element
下面我將展示一種方法,
利用另一個內建 (built-in) 的列表操作
這個操作還未介紹過,它大幅簡化了 find-element
這個操作稱為 index
index 方法 (method) 用於列表
你傳入一個值,index 的輸出是那個值位於列表的位置
所以這個內建 index
幾乎完全按照我們的需求解決了 find-element
不同之處在於,當我們對列表呼叫 index,
如果這個列表不包含我們傳入的值
index 不會傳回 -1,而是給我們 error
看看 Python 解譯器的情況
我要定義變數 p ,並指定列表 [0,1,2] 的值給它
如果我們呼叫 p.index(),傳入 2,我們得到結果是 2
值 2 在 p 裡的位置
第二個例子,在列表裡我們多加兩個 2
我們看到,它總是給我們第一個 2
所以 p.index 傳回的結果,是出現值 2 的第一個位置
現在我們試一個不存於列表中的元素
結果不是得到 -1,而是得到 error
我們要找的標靶 (target) 元素在列表中找不到
所以,如果我們想讓 find-element 完全按照要求
我們不能直接使用 index
還有其他一些列表操作 (list operation),可能很有幫助
總結一下 index 方法 (mehod) 的作用
如果傳入的值存在於列表中,
它傳回這個值出現的第一個位置
這正是我們希望 find-element 做的事
問題在於,如果這個值在列表中找不到,就會產生 error
還有一個列表操作 (list operation)
可以幫助我們使用 index 來寫 find-element
它對其他很多事情也很有用,那就是字組 'in'
我們已經在 for loop 中使用 in
我們在這裡使用同一個字組 in,
但是根據上下文,這裡的意義有些不同
這個語法是在 in 的左邊放一個值,後面跟著一個列表
這個語法與我們之前見到的 Python 語言相比有些奇怪
它看起來不像程序呼叫 (procedure call),
但是用英文對這個內容進行表達時
卻是非常自然的
如果我們說:“ 3 在列表中嗎?”
用 Python 語言寫出來就是 3 in p
看看解譯器如何運作
現在我印出 3 in p 的結果
3 不在列表中,所以印出 False
如果我把它改為印出 2 in p 的結果
我們得到值 True
總結一下 in 運算子的作用
如果值存在於列表中,輸出是 True
否則輸出是 False
類似地,我們可以使用 'not in'
'not in' 與 'in' 相反
如果值不存在於列表中,
< value> not in < list> 的結果是 True
如果這個值存在於列表中,
那麼 < value> not in < list> 的結果是 False
< value> not in < list> 的值完全相等於
not < value> in < list>
採用 not in 的唯一原因是,在英文中,
這比把 not 放在值和 in 之間
讀起來更順一些
現在檢驗你是否理解 index,in 和 not in 等操作
我想讓你試著再次定義 find-element 程序
它跟我們之前的定義功能一模一樣
如果該元素存在,它會給我們搜尋元素出現的位置
如果不存在,它會給我們 -1
但是這次,不使用 while loop 或 for loop 來定義
看看你是否能夠使用 index 來定義它