所以我想找到比出現在列表中多次一些特定號碼的位置。我想要第一個位置。找到第一個出現在列表中[巨蟒]
示例:假設我想3
s = [1,2,3,4,5,3,9,8] => s[2] appears first
所以我想找到比出現在列表中多次一些特定號碼的位置。我想要第一個位置。找到第一個出現在列表中[巨蟒]
示例:假設我想3
s = [1,2,3,4,5,3,9,8] => s[2] appears first
s.index(3)
將返回2
,你的願望。
index
將提高ValueError
如果指定的產品不在列表中。
一點點模糊的問題。
如果你只是想找到特定元素的第一次出現的索引,你應該使用list.index()方法:
index = s.index(3)
但是,如果你
希望找到似乎比 更多一些一旦在名單
一般情況下(沒有給出元素值),似乎你可以
下面的函數返回一個重複的第一次亮相的指數
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
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
除非我誤解你的問題,這應該做的伎倆:
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
這應該給你的第一個元素的第一次出現是多次出現在列表中的索引
如果這不是你以後,請留下評論,我會編輯代碼。
這是做它的另一種方式..
如果存在,它會返回第一個索引.. 如果沒有可用的副本,它會引發IndexError。
[s.index(_) for _ in s if s.count(_) > 1][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
Downvote?這個問題的措辭有點好奇,但基於標題和例子,我認爲我的解釋沒有任何問題。 – Sapph 2011-01-23 05:15:28
你可能只寫了'2`,它會很有用。問題是如何找出哪個項目是重複的。 – 2011-01-23 05:18:25
這顯然不是那麼簡單,否則我不會收到三個upvotes或按照我的方式解釋它。閱讀問題的標題。我完全有可能錯誤地閱讀提問者的意圖,但對於完全陌生的人來說,這是一個完全「有用」的答案。 – Sapph 2011-01-23 05:22:25