使用 Python 列出列表中重复值的索引
Posted
技术标签:
【中文标题】使用 Python 列出列表中重复值的索引【英文标题】:List indexes of duplicate values in a list with Python 【发布时间】:2014-07-01 23:08:36 【问题描述】:我正在尝试修改这个列出重复项的定义,以便它列出重复值的索引。另外,我希望它列出所有重复项,这意味着 a = [1,2,3,2,1,5,6,5,5,5] 的结果将是 duplicate_indexes = [3,4,7 ,8,9] 这是定义:
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in seq if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
【问题讨论】:
【参考方案1】:列表理解打印重复的索引。它将列表切片直到选定的索引,如果该项目已经存在于切片列表中,则返回索引值
a= [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
result=[idx for idx, item in enumerate(a) if item in a[:idx]]
print result #[3, 4, 7, 8, 9]
【讨论】:
与其他答案相比,+1 是最短且最清晰地表达规范。【参考方案2】:a, seen, result = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5], set(), []
for idx, item in enumerate(a):
if item not in seen:
seen.add(item) # First time seeing the element
else:
result.append(idx) # Already seen, add the index to the result
print result
# [3, 4, 7, 8, 9]
编辑:您可以在该函数中使用列表推导,就像这样
def list_duplicates(seq):
seen = set()
seen_add = seen.add
return [idx for idx,item in enumerate(seq) if item in seen or seen_add(item)]
print list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5])
# [3, 4, 7, 8, 9]
【讨论】:
您正在使用seen
的集合来快速进行会员测试?【参考方案3】:
def list_duplicates_index(seq):
return [i for (i,x) in enumerate(a) if x in list_duplicates(a)]
【讨论】:
【参考方案4】:def list_duplicates(seq):
d =
for i in seq:
if i in d:
d[i] += 1
else:
d[i] = 1
dups = []
for i in d:
if d[i] > 1:
dups.append(i)
lst = []
for i in dups:
l = []
for index in range(len(seq)):
if seq[index] == i:
l.append(index)
lst.append(l[1:])
new = []
for i in lst:
for index in i:
new.append(index)
return new
【讨论】:
以上是关于使用 Python 列出列表中重复值的索引的主要内容,如果未能解决你的问题,请参考以下文章