(給Python開發者加星標,提升Python技能)
綜合整理:Python開發者
問題:假設有一個列表["年薪10萬", "年薪30萬", "年薪50萬","年薪100萬"],我想得到元素"年薪100萬"的索引(即3),要怎麼做?
可能最先想到的是對列表進行遍歷,對吧?其實有個很簡單的方式,就是使用List的index函數!
簡潔的解決方法:
["年薪10萬", "年薪30萬", "年薪50萬","年薪100萬"].index("年薪100萬")3雖然使用index這個函數是解決問題最簡潔的方法,但是index函數,它在list的API裡面是相當「弱「的,使用的時候會碰到各種問題。所以雖然解決了問題,但是我們還是要進一步的展開和總結一下index函數。
首先,看一下index函數的完整形式 list.index(x[, start[, end]]),它的功能是返回列表中從第0號數據項開始,第一個等於x的數據項的索引,如果沒有找到x,則返回ValueError。
可選參數start和end用來指定搜索列表的特定範圍內的序列,這時返回的值是相對整個list的起點,而非相對於start參數。
其次,每次調用index函數,都會順序檢查list中的每個元素,直到找到匹配或者返回ValueError。
但是如果你的list很長,並且不知道要找的元素的大概位置,那麼這個搜索過程就會成為程序運行時間的瓶頸。這個時候,你可能需要考慮換種數據結構。
但是如果你知道匹配結果大概位置,你可以給index一點「提示「。例如下面這兩個例子,l.index(999_999,999_990,1_000_000)的執行速度是l.index(999_999)的1萬倍!!因為前一個index完成匹配只搜索了10次,而後一個index函數搜索了近1百萬次!!
import timeittimeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))',number=1000)15.676082027timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l =list(range(0, 1_000_000))', number=1000)0.00032909400000846745第三、index函數隻返回其第一次匹配的索引。調用index的時候,會搜索整個list直到找到一個匹配的值,並停止運行。那麼如果想要返回多個匹配的話,可以使用列表推導式或生成器表達式。
[1, 1].index(1)0[i for i, e in enumerate([1, 2, 1]) if e == 1][0, 2]g = (i for i, e in enumerate([1, 2, 1]) if e == 1)next(g)0next(g)2最後,如果要匹配的元素沒有在list種,則調用index會導致ValueError
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 2 is not in list因此如果要找的元素可能不在list中,應該使用try/except捕捉ValueError異常。
def find_element_in_list(element, list_element): try: index_element = list_element.index(element) return index_element except ValueError: return 'not exists'Tips:最後的最後,附送一個學習Python非常有用的tip:使用help函數!
help(["年薪10萬", "年薪30萬", "年薪50萬","年薪100萬"])得到關於list類的所有方法及說明,當然也包括index函數
class list(object)
...| index(...)
| L.index(value, [start, [stop]]) -> integer
| Raises ValueError if the value is not present.
|
| insert(...)
| L.insert(index, object)
|
| pop(...)
| L.pop([index]) -> item
| Raises IndexError if list is empty or index is out of range....- EOF -
覺得本文對你有幫助?請分享給更多人
關注「Python開發者」加星標,提升Python技能
點讚和在看就是最大的支持❤️