假設我有一個這樣的串列:
l = [1, 2, 3, 4, 5, 3]
我如何獲得那些重復的 3 的索引?
uj5u.com熱心網友回復:
首先,您需要弄清楚哪些元素是重復的以及在哪里。我通過在字典中索引它來做到這一點。
然后你需要提取所有重復的值。
from collections import defaultdict
l = [1, 2, 3, 4, 5, 3]
_indices = defaultdict(list)
for index, item in enumerate(l):
_indices[item].append(index)
for key, value in _indices.items():
if len(value) > 1:
# Do something when them
print(key, value)
輸出:
3 [2, 5]
另一種方法是像這樣過濾掉它們:
duplicates_dict = {key: indices for key, indices in _indices.items() if len(indices) > 1}
uj5u.com熱心網友回復:
您可以使用字典理解一次性獲取所有重復的數字及其索引:
L = [1, 2, 3, 4, 5, 3, 8, 9, 9, 8, 9]
R = { n:rep[n] for rep in [{}] for i,n in enumerate(L)
if rep.setdefault(n,[]).append(i) or len(rep[n])==2 }
print(R)
{3: [2, 5],
9: [7, 8, 10],
8: [6, 9]}
使用 for 回圈的等效項是:
R = dict()
for i,n in enumerate(L):
R.setdefault(n,[]).append(i)
R = {n:rep for n,rep in R.items() if len(rep)>1}
Counter from collections 可用于避免不必要地創建單項串列:
from collections import Counter
counts = Counter(L)
R = dict()
for i,n in enumerate(L):
if counts[n]>1:
R.setdefault(n,[]).append(i)
uj5u.com熱心網友回復:
find deplicates 并回圈遍歷串列以找到相應的索引位置。不是最有效的,但有效
input_list = [1,4,5,7,1,2,4]
duplicates = input_list.copy()
for x in set(duplicates):
duplicates.remove(x)
duplicates = list(set(duplicates))
dict_duplicates = {}
for d in duplicates:
l_ind = []
dict_duplicates[d] = l_ind
for i in range(len(input_list)):
if d == input_list[i]:
l_ind.append(i)
dict_duplicates
uj5u.com熱心網友回復:
這應該做
list = [1,2,3,4,5,3]
deletes = 0;
for element in list:
if element == 3:
print(list.index(element) deletes)
deletes = 1;
list.remove(3)
我們獲取元素的索引,洗掉一個以便它可以找到下一個,并將下一個索引增加 1 以使其與原始串列索引匹配。輸出:
2
5
uj5u.com熱心網友回復:
l = [1,2,3,4,5,3]
for i in range(len(l)):
for j in range(i 1 , len(l)):
if l[i] == l[j]:
z = f"{l[i]} have been repeated in {i} , {j}"
print(z)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394041.html
上一篇:列出沒有唯一列的資料框
