2013-07-16 25 views
7

在Python在開始的數組元素,您可以指定開始和結束搜索的索引時列表元素:搜索一個給定的指標

>>> l = ['a', 'b', 'a'] 
>>> l.index('a') 
0 
>>> l.index('a', 1) # begin at index 1 
2 
>>> l.index('a', 1, 3) # begin at index 1 and stop before index 3 
2 
>>> l.index('a', 1, 2) # begin at index 1 and stop before index 2 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: 'a' is not in list 

是否有紅寶石等的功能?你可以使用數組切片,但由於它需要中間對象,看起來好像效率不高。

回答

1

沒有在Ruby中對等的功能。

您可以從數組的開頭進行搜索,並使用#index前進到末尾,或者從數組的末尾進行搜索並返回到起始位置#rindex。要從一個任意索引轉到另一個索引,必須首先使用數組切片(如#[])將數組切片到感興趣的索引,如OP所示。

0

嘗試了這一點

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

arr[1,3].include? 2 
=> true 
arr[1,3].include? 1 
=> false