有没有人知道如何在python列表中获取重复项的索引位置? 我尝试过这样做,但它只给出了该项在列表中第一次出现的索引。
List = ['A', 'B', 'A', 'C', 'E']
我希望它能给我:
index 0: A
index 2: A
有没有人知道如何在python列表中获取重复项的索引位置? 我尝试过这样做,但它只给出了该项在列表中第一次出现的索引。
List = ['A', 'B', 'A', 'C', 'E']
我希望它能给我:
index 0: A
index 2: A
string_list = ['A', 'B', 'C', 'B', 'D', 'B']
pos_list = []
for i in range(len(string_list)):
if string_list[i] = ='B':
pos_list.append(i)
print pos_list
这是一个好问题,有很多方法可以解决。
下面的代码是其中一种解决方案。
letters = ["a", "b", "c", "d", "e", "a", "a", "b"]
lettersIndexes = [i for i in range(len(letters))] # i created a list that contains the indexes of my previous list
counter = 0
for item in letters:
if item == "a":
print(item, lettersIndexes[counter])
counter += 1 # for each item it increases the counter which means the index
另一种获取索引的方法,但这次存储在列表中
letters = ["a", "b", "c", "d", "e", "a", "a", "b"]
lettersIndexes = [i for i in range(len(letters)) if letters[i] == "a" ]
print(lettersIndexes) # as you can see we get a list of the indexes that we want.
你好
已经有很多回复了,但我真的很喜欢这个解决方案,而且它非常快(它使用pandas.Series,因为它们比pd.DataFrames更快)。
这个解决方案的好处是它忽略了所有重复元素的第一个元素。
import numpy as np
import pandas as pd
lst = [0, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 8, 9, 9]
#index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
#duplicates | | | | |
indices = np.where(pd.Series(lst).duplicated())[0]
print(indices)
# [ 2 4 5 10 14]
setdefault
实例方法的字典方法。List = ['A', 'B', 'A', 'C', 'B', 'E', 'B']
# keep track of all indices of every term
duplicates = {}
for i, key in enumerate(List):
duplicates.setdefault(key, []).append(i)
# print only those terms with more than one index
template = 'index {}: {}'
for k, v in duplicates.items():
if len(v) > 1:
print(template.format(k, str(v).strip('][')))
Counter
,defaultdict
和其他来自collections
的容器类都是dict
的子类,因此也共享setdefault
方法。def dup_list(my_list, value):
'''
dup_list(list,value)
This function finds the indices of values in a list including duplicated values.
list: the list you are working on
value: the item of the list you want to find the index of
NB: if a value is duplcated, its indices are stored in a list
If only one occurence of the value, the index is stored as an integer.
Therefore use isinstance method to know how to handle the returned value
'''
value_list = []
index_list = []
index_of_duped = []
if my_list.count(value) == 1:
return my_list.index(value)
elif my_list.count(value) < 1:
return 'Your argument is not in the list'
else:
for item in my_list:
value_list.append(item)
length = len(value_list)
index = length - 1
index_list.append(index)
if item == value:
index_of_duped.append(max(index_list))
return index_of_duped
# function call eg dup_list(my_list, 'john')
def duplicates(list,dup):
a=[list.index(dup)]
for i in list:
try:
a.append(list.index(dup,a[-1]+1))
except:
for i in a:
print(f'index {i}: '+dup)
break
duplicates(['A', 'B', 'A', 'C', 'E'],'A')
Output:
index 0: A
index 2: A
# note: below list has more than one kind of duplicates
List = ['A', 'B', 'A', 'C', 'E', 'E', 'A', 'B', 'A', 'A', 'C']
d1 = {item:List.count(item) for item in List} # item and their counts
elems = list(filter(lambda x: d1[x] > 1, d1)) # get duplicate elements
d2 = dict(zip(range(0, len(List)), List)) # each item and their indices
# item and their list of duplicate indices
res = {item: list(filter(lambda x: d2[x] == item, d2)) for item in elems}
print(res)
,你会看到这个:{'A': [0, 2, 6, 8, 9], 'B': [1, 7], 'C': [3, 10], 'E': [4, 5]}
这里有一个适用于多个重复项的解决方案,您不需要指定任何值:
List = ['A', 'B', 'A', 'C', 'E', 'B'] # duplicate two 'A's two 'B's
ix_list = []
for i in range(len(List)):
try:
dup_ix = List[(i+1):].index(List[i]) + (i + 1) # dup onwards + (i + 1)
ix_list.extend([i, dup_ix]) # if found no error, add i also
except:
pass
ix_list.sort()
print(ix_list)
[0, 1, 2, 5]
def find_duplicate(list_):
duplicate_list=[""]
for k in range(len(list_)):
if duplicate_list.__contains__(list_[k]):
continue
for j in range(len(list_)):
if k == j:
continue
if list_[k] == list_[j]:
duplicate_list.append(list_[j])
print("duplicate "+str(list_.index(list_[j]))+str(list_.index(list_[k])))
import collections as col
lett_list = ['A', 'B', 'A', 'C', 'E']
lett_dict = {}
counter = col.Counter(lett_list)
elements = [i for i in counter]
for elem in elements:
lett_dict[elem]=[i for i in range(len(lett_list)) if lett_list[i]==elem]
print(lett_dict)
{'A': [0, 2], 'B': [1], 'C': [3], 'E': [4]}