所以我想找到比出现在列表中多次一些特定号码的位置。我想要第一个位置。找到第一个出现在列表中[巨蟒]
示例:假设我想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