![](/img/trans.png)
[英]How to get list of indexes of all occurences of the same value in list of lists?
[英]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.