2011-01-23 23 views

回答

-1
s.index(3) 

將返回2,你的願望。

index將提高ValueError如果指定的產品不在列表中。

+0

Downvote?這個問題的措辭有點好奇,但基於標題和例子,我認爲我的解釋沒有任何問題。 – Sapph 2011-01-23 05:15:28

+0

你可能只寫了'2`,它會很有用。問題是如何找出哪個項目是重複的。 – 2011-01-23 05:18:25

+0

這顯然不是那麼簡單,否則我不會收到三個upvotes或按照我的方式解釋它。閱讀問題的標題。我完全有可能錯誤地閱讀提問者的意圖,但對於完全陌生的人來說,這是一個完全「有用」的答案。 – Sapph 2011-01-23 05:22:25

1

一點點模糊的問題。

如果你只是想找到特定元素的第一次出現的索引,你應該使用list.index()方法:

index = s.index(3) 

但是,如果你

希望找到似乎比 更多一些一旦在名單

一般情況下(沒有給出元素值),似乎你可以

  • 或者做簡單的O(N^2)在陣列(檢查列表的每個元素的所有元素,直到複製被發現的)搜索
  • 或不排序,在排序的列表中找到重複元件,然後找到使用list.index()方法將原始數組中的重複元素索引 - 由於排序,這將取O(N * log(N))。
0

下面的函數返回一個重複的第一次亮相的指數

def find_first_duplicate(num_list): 
     track_list =[] 
     index = 0 
     for e in num_list: 
      if(e not in track_list): 
       track_list += [e] 
      else: ## found! 
       return index 
      index += 1 
4
def first_dup(seq): 
    # keep track of the positions 
    seen = {} 
    for pos,item in enumerate(seq): 
     if item in seen: 
      # saw it before, so its a duplicate 
      return seen[item] 
     else: 
      # first time we see it, store the pos 
      seen[item] = pos 
1

除非我誤解你的問題,這應該做的伎倆:

s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3] 
for i in range(len(s)): 
    if s.count(s[i]) > 1: 
     return i 

這應該給你的第一個元素的第一次出現是多次出現在列表中的索引

如果這不是你以後,請留下評論,我會編輯代碼。

0

這是做它的另一種方式..

如果存在,它會返回第一個索引.. 如果沒有可用的副本,它會引發IndexError。

[s.index(_) for _ in s if s.count(_) > 1][0] 
0

然而,這樣做的另一種方式:

from operator import countOf 

def multindex(seq): 
    """ find index of first value occurring more than once 
     in a sequence, else raise ValueError if there aren't any 
    """ 
    for i,v in enumerate(seq): 
     if countOf(seq, v) > 1: 
      return i 
    else: 
     raise ValueError 

print 's[{}] is first value in the list occurring more than once'.format(multindex(s)) 
# s[2] is first value in the list occurring more than once 
相關問題