簡體   English   中英

如何獲取列表中相同值的索引?

[英]How to get the indexes of the same values in a list?

假設我有一個這樣的列表:

l = [1, 2, 3, 4, 5, 3]

如何獲取那些重復的 3 的索引?

首先,您需要弄清楚哪些元素被重復以及在哪里重復。 我通過在字典中索引它來做到這一點。

然后你需要提取所有重復的值。

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)

Output:

3 [2, 5]

另一種方法是像這樣過濾掉它們:

duplicates_dict = {key: indices for key, indices in _indices.items() if len(indices) > 1}

您可以使用字典理解來獲取一個 go 中的所有重復數字及其索引:

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}

collections 中的Counter可用於避免不必要地創建單個項目列表:

from collections import Counter
counts = Counter(L)
R = dict()
for i,n in enumerate(L):
    if counts[n]>1:
       R.setdefault(n,[]).append(i)

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            

這應該這樣做

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
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)
            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM