【问题标题】:How to get the indexes of the same values in a list?如何获取列表中相同值的索引?
【发布时间】:2021-12-26 16:31:08
【问题描述】:

假设我有一个这样的列表:

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

如何获取那些重复的3的索引?

【问题讨论】:

标签: python arrays list


【解决方案1】:

您可以使用字典推导式一次性获取所有重复的数字及其索引:

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 import Counter
counts = Counter(L)
R = dict()
for i,n in enumerate(L):
    if counts[n]>1:
       R.setdefault(n,[]).append(i)

【讨论】:

  • 恕我直言,我理解需要将所有内容都统一起来,但这段代码效率极低且难以理解。我不确定是否有任何方法可以改善这一班轮。
  • 虽然我同意它很难阅读(而且我可能不会在生产代码中使用它),但它与 for 循环版本一样有效。它只为每个重复数字输出一次 key:values,并使用一个内部字典,该字典包含与 for 循环中初始 R 相同数量的数据(并且更新方式相同)。
  • 你的单行不如循环高效:它为每个项目创建一个新列表,包括重复项。它会为每个项目导致 2 次字典查找,如果该项目存在多次,则为 3 次。
  • 你说得对,我没有考虑额外的查找。
【解决方案2】:

首先,您需要弄清楚哪些元素被重复以及在哪里重复。我通过在字典中索引它来做到这一点。

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

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}

【讨论】:

    【解决方案3】:

    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            
    

    【讨论】:

      【解决方案4】:

      应该这样做

      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
      

      【讨论】:

      • 不知道3有没有重复怎么办?
      • 如果 3 不重复,它将输出唯一的 3 索引,如果它不在列表中,则不会输出任何内容
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多